Why is reusing variables is slowed than creating new variables?

In C++ you can apply the prefix “static” to variables such that every time the variable is redefined, the system does not attempt to allocate any more memory to it.

I assume something similar would be the case in Luau, since creating new instances is far slower than reusing existing ones.

Running the following code:

local t = tick()
local a
for i = 0, 1e9 do
   a = i
end
print(tick() - t) -- Time taken in seconds: 6.323152780532837
local t = tick()
for i = 0, 1e9 do
   local a
   a = i
end
print(tick() - t) -- Time taken in seconds: 2.804739236831665

Contrary to my expectations, reusing variables is over 2 times slower than defining new ones.

I have yet to check the memory consumption since I’m not too sure how to go about doing that.

Feel free to replicate this yourself and share your result.

1 Like

This does not appear to be the case when I benchmark it. In fact, declaring a and then assigning it within the same iteration is actually the slowest, while directly assigning a is the fastest.
The result of declaring a outside of the loop and then constantly redefining it falls within the margin of error as well.

		["local a; loop; a = i"] = function(Profiler)
			local a
			for i = 1, 1e7 do
				a = i
			end
		end;

		["local a; a = i"] = function(Profiler)
			for i = 1, 1e7 do
				local a
				a = i
			end
		end;
		
		["local a = i"] = function(Profiler)
			for i = 1, 1e7 do
				local a = i
			end
		end;
1 Like

I tried your original benchmark as well:
image

Interesting…
I wonder why my results were so different

This is partially because of the way Lua’s scopes work. The first example requires the scope to obtain a non-constant upvalue (a), alter it and push an update back to it.

The second one on the other hand, creates a localized variable that gets changed once and GC’d after the scope ends. It doesn’t need to push any update between scopes because a will only exist in that scope.

Do note these results are entirely deterministic and you shouldn’t try to incorporate micro-optimizations like this, since chances are as time goes on the better Luau’s VM will handle these.

1 Like

I see.
Though, what are the differences between my environment and @Prototrode’s that would cause the disparity in our results?

I tried your benchmark code too, small difference:
image