Originally Posted by lyravega
Performance is a primary concern for my code, as it is time critical. For example, a simple code, which is time critical (expected to finish 100 runs in a second at least):
Code:
for derp = 1, 100 do
x = y * z
end
vs
Code:
for derp = 1, 100 do
local y = y
local z = z
x = y * z
end
For this little stupid code above, since the variables are used only once, making a local variable "feels" like it slows the process down, as instead of just using these variables, it will have to make a local and assign those variables to these locals, taking the extra mile. However, I can see a performance benefit if a variable was used more than once.
A general question would be, is there a case that locals should be avoided?
|
Actually, in that case where it's only used once, you don't get a time savings.
Setting up sample:
Warning: Spoiler
Lua Code:
nitr = 10000000
x = 10
y = 20
tstart, tend = 0, 0
tstart = os.clock()
for i = 1,nitr do
z = x * y
end
tend = os.clock()
print( tend - tstart )
tstart = os.clock()
for i = 1,nitr do
local x, y, z = x, y
z = x * y
end
tend = os.clock()
print( tend - tstart )
10 million iterations of this take about .5sec on my computer and the difference between the two is negligible. Successive runs will even flip which one is faster.
However, multiple access is where you do start to notice a difference (in 10 million runs).
Putting the "z = x*y" three times per loop, you get around 1.65s versus 0.94s
Where you get the savings is in lookups to the global table. When you only use the global once, you still have to look it up once to create the local variable.
Also, I can't stress this enough:
I had to go to millions of iterations to get a measurable difference.
If you find yourself needing this level of optimization, please 1) evaluate whether you really need to run that many operations that frequently and 2) use some profiling tools so you can see where you're eating up your time. Switching to local does squat if your main bottleneck is removing elements using table.remove() from the front of a table.