lua-users home
lua-l archive

Re: Using Lua's string interning for faster compares?

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi!
On 17.01.2012 08:12, HyperHacker wrote:
When I write modules to wrap C++ objects, they usually have a __index
method that does a lot of string comparing, like:
if(!strcmp(key, "foo")) lua_pushcfunction(L, obj_method_foo);
else if(!strcmp(key, "bar")) lua_pushcfunction(L, obj_method_bar);
etc... I'm not sure if compilers can optimize this, but doing all
those strcmp()s every time a method/field is looked up seems terribly
inefficient.
Try Ragel[1].
 [1]: http://www.complang.org/ragel/
I've attached the template I use for such occasions.
HTH,
Philipp
/* This is a template for matching one of multiple strings using the
 * ragel state machine compiler. Edit/extend the state machine and the
 * defines below. If using more than one state machine in a C file,
 * the exported function name must be redefined.
 * Compile (to str2id.h):
 * $ ragel -C -G2 str2id.rh
 * For graphviz output:
 * $ ragel -V -p str2id.rh | dot -T png -o out.png
 */
#define STR2ID_FUNC_NAME str2id
#define ID_FOO 0
#define ID_BAR 1
#define ID_BAZ 2
#define ID_FOOBAR 3
#define ID_HELLO 4
#define ID_BYE 5
%%{
 machine s2i;
 main :=
 "foo" %/{ return ID_FOO; } |
 "bar" %/{ return ID_BAR; } |
 "baz" %/{ return ID_BAZ; } |
 "foobar" %/{ return ID_FOOBAR; } |
 "hello" %/{ return ID_HELLO; } |
 "bye" %/{ return ID_BYE; };
}%%
/* DO NOT CHANGE ANYTHING BELOW THIS COMMENT! */
#include <stddef.h>
static unsigned STR2ID_FUNC_NAME( char const* p, size_t n ) {
 char const* pe = p + n;
 char const* eof = pe;
 int cs = 0;
%%{
 write data;
 write init;
 write exec;
}%%
 (void)s2i_en_main;
 (void)s2i_error;
 (void)s2i_first_final;
 return -1;
}
#undef STR2ID_FUNC_NAME

AltStyle によって変換されたページ (->オリジナル) /