Skip to content

Instantly share code, notes, and snippets.

@DarkWiiPlayer
Last active May 16, 2019 12:16
Show Gist options
  • Save DarkWiiPlayer/9679bcff1192157e3d9f5e7d8ced7902 to your computer and use it in GitHub Desktop.
Save DarkWiiPlayer/9679bcff1192157e3d9f5e7d8ced7902 to your computer and use it in GitHub Desktop.
Benchmark for memoization of a simple index translation function
local ffi = require 'ffi'
local intidx_fnc do
if ffi.abi('le') then
function intidx_fnc(n)
if n<1 or n>4 then
error("wrong index", 2)
end
return n-1
end
else
function intidx_fnc(n)
if n<1 or n>4 then
error("wrong index", 2)
end
return 4-n
end
end
end
local intidx_tab do
intidx_tab = setmetatable({}, {__index = function(self, index)
local res = intidx_fnc(index)
rawset(self, index, res)
return res
end})
end
local function bench(f)
local before = os.clock()
f()
return os.clock() - before
end
local function compare(vals)
for key, value in pairs(vals) do
print(key, bench(value))
end
end
local num = 1e9
compare {
['function'] = function()
for i=1,num do
local a = intidx_fnc(i % 3 + 1)
end
end;
['table'] = function()
for i=1,num do
local a = intidx_tab[i % 3 + 1]
end
end;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment