Originally Posted by Aezay
Is there any performance benefits in assigning multiple variables at the same times compared to one per line?
Code:
tbl.name, tbl.value, tbl.color = name, value, color;
tbl.name = name;
tbl.value = value;
tbl.color = color;
|
Code:
local clock = os.clock
local insert, sort = table.insert, table.sort
local orderednames = {}
local names = setmetatable({}, {__newindex = function(t, k, v)
insert(orderednames, k)
rawset(t, k, v)
end})
local function bench(name, func, ...)
local start = clock()
for i = 1, 1e7 do
func(...)
end
names[name] = clock() - start
end
local function printresults()
sort(orderednames, function(a, b)
return names[a] < names[b]
end)
for i, v in pairs(orderednames) do
print(string.format("%d %s took %.5f secs", i, v, names[v]))
end
end
local tbl = {}
tbl.cat, tbl.dog, tbl.cow, tbl.pig = "Meow", "Woof", "Moo", "Oink"
bench("1 line assign", function()
tbl.cat, tbl.dog, tbl.cow, tbl.pig = "Meow", "Woof", "Moo", "Oink"
end)
bench("multi line assign", function()
tbl.cat = "Meow"
tbl.dog = "Woof"
tbl.cow = "Moo"
tbl.pig = "Oink"
end)
printresults()
I'm consistently getting these results
Code:
1 multi line assign took 11.77000 secs
2 1 line assign took 12.55000 secs
I can't explain it.