Skip to content

Instantly share code, notes, and snippets.

@Stepets Stepets/arr.lua
Created May 29, 2016

Embed
What would you like to do?
local N = 10000
local function run_original_proxy()
local arr = setmetatable({length = 0}, {
__newindex = function(t,k,v)
if type(k) == 'number' and k >= t.length then
t.length = k + 1
end
rawset(t,k,v)
end
})
local t1 = os.clock()
for i = 1, N do
arr[i] = i
end
local t2 = os.clock()
for i = 1, N do
arr[i] = -arr[i]
end
local t3 = os.clock()
return t2 - t1, t3 - t2
end
local function run_simple_proxy()
local data = {}
local arr = setmetatable({length = 0}, {
__newindex = function(t,k,v)
local len = t.length
t.length = k >= len and (k + 1) or len
rawset(t,k,v)
end
})
local t1 = os.clock()
for i = 1, N do
arr[i] = i
end
local t2 = os.clock()
for i = 1, N do
arr[i] = -arr[i]
end
local t3 = os.clock()
return t2 - t1, t3 - t2
end
local function run_without_proxy()
local data = {}
local arr = {}
local t1 = os.clock()
for i = 1, N do
arr[i] = i
end
local t2 = os.clock()
for i = 1, N do
arr[i] = -arr[i]
end
local t3 = os.clock()
return t2 - t1, t3 - t2
end
local time = {
simple = {},
original = {},
without = {}
}
local function get_avg_time(arr)
local sum = {
init = 0,
modify = 0
}
for i = 1, #arr do
sum.init = sum.init + arr[i].init
sum.modify = sum.modify + arr[i].modify
end
sum.init = sum.init / #arr
sum.modify = sum.modify / #arr
return sum
end
for i = 1, 100 do
print(i .. "/100")
local result = {run_simple_proxy()}
table.insert(time.simple, {init = result[1], modify = result[2]})
result = {run_original_proxy()}
table.insert(time.original, {init = result[1], modify = result[2]})
result = {run_without_proxy()}
table.insert(time.without, {init = result[1], modify = result[2]})
end
local average = {
simple = get_avg_time(time.simple),
original = get_avg_time(time.original),
without = get_avg_time(time.without)
}
print("average time original metatable")
print("init:", average.original.init, "modify:", average.original.modify)
print("average time simple metatable")
print("init:", average.simple.init, "modify:", average.simple.modify)
print("average time without metatable")
print("init:", average.without.init, "modify:", average.without.modify)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.