Skip to content

Instantly share code, notes, and snippets.

@catwell
Last active December 28, 2015 21:19
Embed
What would you like to do?
timing different ways to apply a function to elements of a sequence
local map = function(f, l)
local r = {}
for i=1,#l do r[i] = f(l[i]) end
return r
end
local map2 = function(f, l)
for i=1,#l do l[i] = f(l[i]) end
return l
end
local l = {}
for i=1,1000000 do l[i] = i end
local f = function(x) return 2*x end
local t0 = os.clock()
map(f, l)
local t1 = os.clock()
local l2 = {}
for i=1,#l do l2[i] = l[i] end
map2(f, l2)
local t2 = os.clock()
map2(f, l)
local t3 = os.clock()
print("functional map:", t1-t0)
print("copy + mutate:", t2-t1)
print("only mutate:", t3-t2)

Lua 5.1

functional map:	0.143831
copy + mutate:	0.21176
only mutate:	0.133798

LuaJIT 2.0

functional map:	0.021932
copy + mutate:	0.024511
only mutate:	0.004763
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment