[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Using Lua's string interning for faster compares?
- From: dcharno <dcharno@...>
- Date: Thu, 19 Jan 2012 23:05:39 -0500
On 01/18/2012 01:07 AM, Philipp Janda wrote:
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.
What about gperf?
http://www.gnu.org/software/gperf/
%includes
struct str2id_s { const char *name; int id; };
%%
"foo", 0
"bar", 1
"baz", 2
"foobar", 3
"hello", 4
"bye", 5
%%
#include <stdio.h>
int str2id(const char *s)
{
struct str2id_s *p = in_word_set(s, strlen(s));
return p ? p->id : -1;
}
int main(int argc, char *argv[])
{
printf( "%d \n", str2id("foo") );
printf( "%d \n", str2id("bar") );
printf( "%d \n", str2id("baz") );
}