Skip to content

Commit

Permalink
Optimize tic api call performance in LUA.
Browse files Browse the repository at this point in the history
Previously, the tic_core* was associated with a global variable named "_TIC80" and every api call fetches the tic_core by finding the global with this name. Finding the global variable with that name took surprising amount of time, according to profiling. With this optimization, each API function is associated with tic_core* through lua_pushcclosure mechanism. Closures are functions that are associated with certain "upvalues". Fetching an upvalue is very fast in LUA.

checkForceExit still fetches the tic_core from the global, as the hook is an ordinary function, not a global.
  • Loading branch information
vsariola committed Oct 10, 2021
1 parent 60e63de commit 3b4331b
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/api/lua.c
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,18 @@ static s32 getLuaNumber(lua_State* lua, s32 index)

static void registerLuaFunction(tic_core* core, lua_CFunction func, const char *name)
{
lua_pushcfunction(core->currentVM, func);
lua_pushlightuserdata(core->currentVM, core);
lua_pushcclosure(core->currentVM, func, 1);
lua_setglobal(core->currentVM, name);
}

static tic_core* getLuaCore(lua_State* lua)
{
tic_core* core = lua_touserdata(lua, lua_upvalueindex(1));
return core;
}

static tic_core* getLuaCoreGlobal(lua_State* lua)
{
lua_getglobal(lua, TicCore);
tic_core* core = lua_touserdata(lua, -1);
Expand Down Expand Up @@ -1356,7 +1363,7 @@ static void lua_open_builtins(lua_State *lua)

static void checkForceExit(lua_State *lua, lua_Debug *luadebug)
{
tic_core* core = getLuaCore(lua);
tic_core* core = getLuaCoreGlobal(lua);

tic_tick_data* tick = core->data;

Expand Down

0 comments on commit 3b4331b

Please sign in to comment.