lua-users home
lua-l archive

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


Hi, Miles!

19.12.09, 23:22, "Miles Bader" <miles@gnu.org>:
> Here's the "optional table" version, which is sort of in between:
>    $ time lua -e 'function f(a,b,c) if type (a) == 'table' then b = a.b c = a.c a = a.a end return a+b+c end; sum = 0; for x = 1, 5000000 do sum = sum + f(x, x+1, x+2) end; print(sum)'
>    37500022500000
>    real    0m2.004s
>    user    0m2.000s
>    sys     0m0.004s

AFAIK, type() uses lua_pushstring(luaL_typename(...)), so it adds amount
of time here. I tested type(v) vs xtype(v) vs f(v), where xtype is
self-written C closure w/upvalues, and f(v) does nothing:

(unrelated to your benchmarks) (all globals)
type: 3.255u
xtype: 2.240u
f: 2.225u


If list will find it useful, here is the source:


static int
xtype(lua_State *L)
{
    static const int is[] = {
        1,  // -1 = LUA_TNONE          => [1] = "nil"
        1,  //  0 = LUA_TNIL           => [1] = "nil"
        4,  //  1 = LUA_TBOOLEAN       => [4] = "boolean"
        8,  //  2 = LUA_TLIGHTUSERDATA => [8] = "userdata"
        2,  //  3 = LUA_TNUMBER        => [2] = "number"
        3,  //  4 = LUA_TSTRING        => [3] = "string"
        5,  //  5 = LUA_TTABLE         => [5] = "table"
        6,  //  6 = LUA_TFUNCTION      => [6] = "function"
        8,  //  7 = LUA_TUSERDATA      => [8] = "userdata"
        7   //  8 = LUA_TTHREAD        => [7] = "thread"
    };
    int      type;

    type = lua_type(L, 1);

    if (-1 <= type && type <= 8)
        lua_pushvalue(L, lua_upvalueindex(is[type+1]));
    else
        lua_pushstring(L, luaL_typename(L, 1));
    return 1;
}
....
lua_pushliteral(L, "nil");
lua_pushliteral(L, "number");
lua_pushliteral(L, "string");
lua_pushliteral(L, "boolean");
lua_pushliteral(L, "table");
lua_pushliteral(L, "function");
lua_pushliteral(L, "thread");
lua_pushliteral(L, "userdata");
lua_pushcclosure(L, xtype, 8);
lua_setglobal(L, "xtype");



-- 
Artur