I am not sure how this ends up working out, but, for a lot of questions you can check out the luau source code now. In this case I’m not sure where the code related to local allocation is.
One thing I would like to mention since your example code follows this pattern, waiting in a while loop is not ideal. You’re really just spreading out lag, and slowing your code down, and if all of your code is slowed down, you might as well just be creating artificial lag.
From my understanding, the way that local allocation works is fairly smart, I would not expect the bottom case to be any faster than the top case except with millions of iterations.
Here’s a benchmark using @boatbomber’s benchmarking tool:
This is showing the time it takes for 100 reads/writes with the local defined inside and outside of the loop.
local iterations = 100
local something = 123
return {
ParameterGenerator = function()
return
end;
Functions = {
["Read locals outside"] = function(Profiler)
for i=1, iterations do
i = something
end
end;
["Read locals inside"] = function(Profiler)
for i=1, iterations do
local something = 123
i = something
end
end;
["Write locals outside"] = function(Profiler)
for i=1, iterations do
something = i
i = something
end
end;
["Write locals inside"] = function(Profiler)
for i=1, iterations do
local something = 123
something = i
i = something
end
end;
};
}
As you can see, the difference is within 0.1 microseconds for both. So, while putting the variables outside the loop is technically faster, in your example the cost is only 0.1 microseconds every single second, which, is practically nothing.
You would need to be running a loop roughly more than a million times before the savings could start to have any noticeable effect on the framerate (>1+ms) at which point the cost of the read/write itself is significantly more expensive.
Plus, this is bound to change plenty, so, really you should just follow whatever makes the most sense from a programming point of view, and if you need to change it for a large loop, you can.