Skip to content

Instantly share code, notes, and snippets.

@nefftd
Created October 16, 2014 22:15
Show Gist options
  • Save nefftd/058816cc6bca1a5fde2a to your computer and use it in GitHub Desktop.
Save nefftd/058816cc6bca1a5fde2a to your computer and use it in GitHub Desktop.
-- In the above we have an interesting tradeoff. Recursion doesn't waste table
-- every invocation, so it's not pushing the GC hard. However, it internally
-- pushes and pops values from the stack every iteration. Whereas the array
-- method only needs to allocate a single stack slot, and after all is really
-- just a standard C array, which ought to be quite efficient. Which is more
-- efficient is not easy to tell.
-- Here, we have a test:
do
local types = {nil,true,0,'string',io.stdout,function()end,print,coroutine.create(function()end),{}}
local n_types = 9
local tests = {1,10,20,50,100,500,1000}
for i = 1,#tests do
local n_args = tests[i]
local args = {}
for i = 1,n_args do
args[i] = types[math.random(n_types)]
end
-- Wrap this in a function so we're not including the overhead of unpacking
-- the args array in the profiling, but rather grabbing them from the stack.
(function(...)
local ITER = 10000
local s
collectgarbage('collect')
local t = os.clock()
for i = 1,ITER do
s = tsa_r(...)
end
print('recursion ('..n_args..'):',os.clock()-t)
collectgarbage('collect')
local t = os.clock()
for i = 1,ITER do
s = tsa_a(...)
end
print('array ('..n_args..'): ',os.clock()-t)
end)(unpack(args,1,n_args))
print(' ')
end
end
-- On my i5 2520M, recursion is more efficient with very few args (1). At 20
-- args, these two methods take almost exactly the same amount of time. Above
-- that the array method starts to take considerably less time. At 500 it's
-- faster by a factor of more than two, and at 1000 it's faster by an order of
-- magnitude.
-- Obviously we probably don't need to tostringall() more than 10 arguments at a
-- time. However, this test serves to compare the two primary methods of
-- manipulating a list of values in general within Lua, which is not uncommon.
-- This may not be a hugely comprehensive test, but it does favor my initial
-- suspicions: recursion for small lists, array w/ iteration for large lists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment