lua-users home
lua-l archive

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



On Tue, Oct 12, 2010 at 11:09 AM, Rebel Neurofog <rebelneurofog@gmail.com> wrote:
I've been thinking about Lua string uniqueness and though out of the
optimization could be made:

===============================
static const char *strconst_rgba = "rgba";
static const char *strconst_rgba = "rgb";
static const char *strconst_rgba = "abgr";
static const char *strconst_rgba = "bgr";

static int some_c_function (lua_State *L)
{
   if (lua_gettop (L) != 1) return 0;
   const char *arg = lua_tostring (L, 1);
    /* no 'strcmp ()' here: */
   if (arg == strconst_rgba) {
       lua_pushnumber (L, 1);
       return 1;
   } else if (arg == strconst_rgb) {
       lua_pushnumber (L, 1);
       return 1;
   } else if (arg == strconst_abgr) {
       lua_pushnumber (L, 1);
       return 1;
   } else if (arg == strconst_bgr) {
       lua_pushnumber (L, 1);
       return 1;
   }
   return 0;
}

int main ()
{
   lua_State *L = luaL_newstate ();
   assert (lua_loadstrconst (L, strconst_rgba)); /* Check for uniqueness */
   assert (lua_loadstrconst (L, strconst_rgb)); /* Check for uniqueness */
   assert (lua_loadstrconst (L, strconst_abgr)); /* Check for uniqueness */
   assert (lua_loadstrconst (L, strconst_bgr)); /* Check for uniqueness */

   /* bind 'some_c_function ()' here */
   /* execute some code */

   return 0;
}
=======================

The primary idea is to avoid 'strcmp ()'.
Instead we compare pointers (just the way things work inside Lua VM).

What do you think? Is it too mad?

P. S. luaL_checkoption () uses strcmp ()


I'd assume that strcmp() is already pretty heavily optimised. Compilers will inline it when at least one of the two args is a literal or a local const (at least that's what was happening 15 years ago, been a while since I worked on a compiler). And I'd be slightly shocked if it didn't already do the pointer comparison before jumping into byte comparisons.

Robby