I wonder if there’s an easy rule for how many times I can directly index a variable before creating a new variable for it becomes a more optimal solution.
For example, when will this
if foo[item.Name] then
foo[item.Name] = 13
else
foo[item.Name] = false
end
Be faster than this
local name = item.Name
if foo[name] then
foo[name] = 13
else
foo[name] = false
end
Yes I could always run tests, but I wondering if there’s a general rule to follow.
StonksMcHat:
Be faster than this
It seems to be the same.
But you can do a benchmark using this idea:
Just to confirm that functions declared as Local are REALLY faster than global functions, I created a benchmark below:
local elements = 100000000
local keyToFind = "k" .. elements
function GlobalFunction()
return true
end
local function LocalFunction()
return true
end
-- benchmark
local time = tick()
for i = 1, elements do
GlobalFunction()
end
local timeG = tick() - time
print("seconds to run a Global function:\t", timeG)
local time = tick()
for i = 1, elements do
LocalFunction()
end…
Forummer
(Forummer)
September 8, 2022, 11:02pm
#3
I tend to create references for objects/properties/values that I intend to use multiple times (more than once) in order to avoid repeating myself.
Just be wary of the local variable/upvalue limits.
Local variables: 200 per function (same as all versions of Lua, this includes function arguments)
Upvalues: 200 per function (up from 60 in Lua 5.1)
Registers: 255 per function (same as all versions of Lua, this includes local variables and function arguments)
Constants: 2^23 per function (up from 2^18 in Lua 5.1)
Instructions: 2^23 per function (up from 2^17 in Lua 5.1, although in both cases the limit only applies to control flow)
Nested functions: 2^15 per function (down from 2^18 in Lua 5.1)
Stack depth: 20000 Lua calls per Lua thread, 200 C calls per C thread (e.g. coroutine.resume
/ pcall
nesting is limited to 200)