- memory aligned for fast access
- no memory wastage
I am into making a simulation which will require a LOT of Vectors.
I know lua tables does a lot of memory wastage.
So, I tried benchmarking the three effective ways of implementing such a structure :-
- lua table
- closure
- ffi
Astonishingly, I found ffi to be much slower than the rest. I heard it supposed to be drastically faster?
Here's the code I tried:
Code: Select all
local ffi = require("ffi")
function vek(a, b)
return function(x)
if x == 1 then return a else return b end
end
end
function vef(a, b)
ffi.cdef[[
typedef struct { int64_t x, y; } vec2;
]]
local vec2 = ffi.new("vec2")
vec2.x = a
vec2.y = b
return vec2
end
function vec(a, b)
return {a, b}
end
local a = vec(1, 2)
local b = vek(1, 2)
local c = vef(1, 2)
print(a[1], a[2])
print(b(1), b(2))
print(c.x, c.y)
-- benchmark tables
local s = os.clock()
local sum = 0
for i = 1, 999999999 do
sum = sum + (a[1] * a[1] + a[2] * a[2])
end
print(sum, ", lua tables: ", os.clock() - s)
-- benchmark closures
local s1 = os.clock()
local sum1 = 0
for i = 1, 999999999 do
sum1 = sum1 + (b(1) * b(1) + b(2) * b(2))
end
print(sum1, ", closures: ", os.clock() - s1)
-- benchmark ffi
local sum2 = ffi.cast("int64_t", 0)
local s2 = os.clock()
for i = 1, 999999999 do
sum2 = sum2 + (c.x * c.x + c.y * c.y)
end
print(sum2, ", ffi struct : ", os.clock() - s1)
Code: Select all
1 2
1 2
1LL 2LL
4999999995 , lua tables: 0.707674
4999999995 , closures: 0.708508
4999999995LL , ffi struct : 0.946042