Skip to content

Instantly share code, notes, and snippets.

@appgurueu
Created February 20, 2023 18:44
Show Gist options
  • Save appgurueu/b3dc90ae45765dd8ff37a510d72ca6bf to your computer and use it in GitHub Desktop.
Save appgurueu/b3dc90ae45765dd8ff37a510d72ca6bf to your computer and use it in GitHub Desktop.
Pathological example to show that due to upvalue copying locals can in fact be slightly slower than globals (environmentals)
local vars = {}
for i = 1, 50 do table.insert(vars, ("v%d"):format(i)) end
local all_vars, all_vals = table.concat(vars, ", "), "1" .. (", 2"):rep(#vars - 1)
local pathological_code = ([[
local %s = %s
return function(get_all)
if get_all then return %s end
return v1
end
]]):format(all_vars, all_vals, all_vars)
local pathological_chunk = assert(loadstring(pathological_code))
setfenv(pathological_chunk, {})
local pathological_func = pathological_chunk()
local sane_code = ([[
%s = %s
return function(get_all)
if get_all then return %s end
return v1
end
]]):format(all_vars, all_vals, all_vars)
local sane_chunk = assert(loadstring(sane_code))
setfenv(sane_chunk, {})
local sane_func = sane_chunk()
local t = os.clock()
for _ = 1, 1e9 do
pathological_func()
end
print("locals", os.clock() - t)
t = os.clock()
for _ = 1, 1e9 do
sane_func()
end
print("envs", os.clock() - t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment