# HG changeset patch # User jbe # Date 1407971484 -7200 # Node ID 035b58aa430a39af02fbde0b439ba2d35b9942e2 # Parent 9fd7e1bf9fe31e2e1c0730b52ff7014418334c89 Improve performance of pairs and ipairs in JSON library diff -r 9fd7e1bf9fe3 -r 035b58aa430a libraries/json/json.c --- a/libraries/json/json.c Tue Aug 12 01:01:54 2014 +0200 +++ b/libraries/json/json.c Thu Aug 14 01:11:24 2014 +0200 @@ -865,12 +865,7 @@ static int json_pairs_iterfunc(lua_State *L) { // stack shall contain two function arguments: lua_settop(L, 2); - // replace first argument with its shadow table - // or throw error if no shadow table is found: - json_getshadow(L, 1); - if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found"); - lua_replace(L, 1); - // get next key value pair from shadow table (using previous key from argument 2) + // get next key value pair from shadow table (argument 1) using previous key (argument 2) // and return nothing if there is no next pair: if (!lua_next(L, 1)) return 0; // replace null-marker with nil: @@ -887,9 +882,10 @@ static int json_pairs(lua_State *L) { // require one argument to function luaL_checkany(L, 1); - // return triple of function json_pairs_iterfunc, first argument, and nil: + // return triple of function json_pairs_iterfunc, shadow table of first argument, and nil: lua_pushcfunction(L, json_pairs_iterfunc); - lua_pushvalue(L, 1); + json_getshadow(L, 1); + if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found"); lua_pushnil(L); return 3; } @@ -901,20 +897,16 @@ lua_settop(L, 2); // calculate new index by incrementing second argument: idx = lua_tointeger(L, 2) + 1; - // push shadow table onto stack position 3 - // or throw error if no shadow table is found: - json_getshadow(L, 1); - if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found"); - // do integer lookup in shadow table and store result on stack position 4: - lua_rawgeti(L, 3, idx); + // do integer lookup in shadow table and store result on stack position 3: + lua_rawgeti(L, 1, idx); // return nothing if there was no value: - if (lua_isnil(L, 4)) return 0; + if (lua_isnil(L, 3)) return 0; // return new index and // either the looked up value if it is not equal to the null-marker // or nil instead of null-marker: lua_pushinteger(L, idx); - if (json_isnullmark(L, 4)) lua_pushnil(L); - else lua_pushvalue(L, 4); + if (json_isnullmark(L, 3)) lua_pushnil(L); + else lua_pushvalue(L, 3); return 2; } @@ -923,9 +915,10 @@ static int json_ipairs(lua_State *L) { // require one argument to function luaL_checkany(L, 1); - // return triple of function json_ipairs_iterfunc, first argument, and zero: + // return triple of function json_ipairs_iterfunc, shadow table of first argument, and zero: lua_pushcfunction(L, json_ipairs_iterfunc); - lua_pushvalue(L, 1); + json_getshadow(L, 1); + if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found"); lua_pushinteger(L, 0); return 3; }