lua-users home
lua-l archive

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


It makes the C code a bit uglier, but I try to use upvalues for all my
Lua string constants in C functions that need to be efficient. By
pre-interning the strings, string equality is reduced to a pointer
compare. Using the registry is another approach, and one that looks a
lot cleaner, but isn't quite as efficient.

Ben

On 5/16/05, Chris Marrin <chris@marrin.com> wrote:
> I want to optimize string compares and pushes when interacting with Lua.
> For instance, in my __index() function I want to do this:
> 
>     const char* prop = lua_getstring(L, -1);
>     if (prop == mygPrototypeString)
>         ...
>     else if (prop == mygParentString)
>         ...
> 
> and so on. The global strings would be created in some init code like this:
> 
>     // global variables
>     const char* mygPrototypeString = NULL;
>     const char* mygParentString = NULL;
> 
>     ...
> 
>     lua_pushstring(L, "prototype");
>     mygPrototypeString = lua_tostring(L, -1);
>     lua_pop(L, 1);
>     lua_pushstring(L, "parent");
>     mygParentString = lua_tostring(L, -1);
>     lua_pop(L, 1);
> 
> By doing some experimentation it looks like, whenever you push a string
> and then ask for a pointer to it, the same address is always returned
> for that pointer, whether it is still on the stack or not. Is this
> always true? Can the above reliably be used to handle strings as atoms?
> 
> Or is there another, better way to do this?
> 
> PS - I am imagining also adding some refs (luaL_ref/luaL_unref) to
> global strings like this so I can push them by just pushing the ref. I
> would do this to save the time of hashing the string. Would this save
> enough to be worth it?
> 
> --
> chris marrin                ,""$,
> chris@marrin.com          b`    $                             ,,.
>                         mP     b'                            , 1$'
>         ,.`           ,b`    ,`                              :$$'
>      ,|`             mP    ,`                                       ,mm
>    ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
>   m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
>  b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
> b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
> P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
>  ```"```'"    `"`         `""`        ""`                          ,P`
> "As a general rule,don't solve puzzles that open portals to Hell"'
>