Does this worsen performance?

If I have a loop, for example one which changes the position of an object, would it worsen performance “creating” variables like position everytime the loop repeats itself, instead of creating the variables before the loop starts and changing them everytime the loop repeats?

If you don’t understand what I mean, its this:

(warning: not real code obviously lol)

Would this take up more performance:

repeat every frame
       local newPos = block.position + 1
       block.position = newPos

than this:

local newPos 
repeat every frame
       newPos = block.position + 1
       block.position = newPos
1 Like

No. The first one is better if you don’t need the newPos variable outside the scope of the loop.

Either way is fine as far as performance, though you should keep variables in the most specific scope that you need them in (good practice).

2 Likes

I can’t imagine the difference between updating and overwriting a single variable will amount to much, when compared to the resources of repositioning the block every frame.

The code you provided doesn’t require variables in the first place.

while true do
    block.Position += Vector3.new(0,1,0)
    task.wait()
end

To answer your question, both of those have the same performance and if not, it’s a very negligible difference. It’s almost the same as indexing a table (but in this case it is indexing the environment), which is not very heavy on performance as is.

Wouldn’t the first one be worse performance wise tho because the garbage collector doesn’t immediately pick up the newPos variable?