[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Using Lua's string interning for faster compares?
- From: Peter Cawley <lua@...>
- Date: Tue, 17 Jan 2012 12:04:31 +0000
On Tue, Jan 17, 2012 at 7:12 AM, HyperHacker <hyperhacker@gmail.com> 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.
>
> Of course there are various ways to improve on this design (return a
> table containing the fields instead of using __index, redirecting the
> lookup to a table, etc), but they do have various drawbacks. This
> method is nice and simple - just not very fast.
>
> I find myself wondering, why is my module doing dumb string compares
> all the time, when Lua fixes this using string interning and hashing?
> It could be much more efficient if I could just push the names of my
> methods into a table in the registry or some such, and use a method
> like lua_tohash() to get their hashes. The series of strcmp()s could
> then be changed to a series of much faster integer compares.
>
> --
> Sent from my toaster.
>
In one of my current projects, I have a similar need to frequently
switch over a Lua string. I opted for a solution of hash-based
dispatch combined with code generation, which I don't think I've seen
proposed on lua-l recently. I've written up a description of the
approach as a blog post:
http://www.corsix.org/content/switch-lua-strings