Does reducing constant variable declarations improve performance?

Hi, I was working on a script and I was curious if this line of code

local nextPosition
	
	while mobHum.Health > 0 do
		nextPosition = "placeholder"
		local path = pathFindingService:CreatePath()
		task.wait()
	end

Would be better then this code in terms of performance:

while mobHum.Health > 0 do
		local nextPosition = "placeholder"
		local path = pathFindingService:CreatePath()
		task.wait()
	end
2 Likes

Declaring the variable shouldn’t affect performance at all.

1 Like

I think it would, but only by a miniscule amount.

2 Likes

There indeed is a difference in the performance, but it is so small that you absolutely don’t need to care about it. But it is generally preffered to make variables completely private for a function, if the function is the only piece of code which stores or reads values from it.

1 Like

It’s a tradeoff. By making the variable outside of the scope, you are possibly using up more memory, but you have better performance.

1 Like

Oh wow, I didn’t think of scope having a impact on memory

1 Like

Well, only sometimes. It might actually save memory to have it out of scope if you are using the variable elsewhere.

1 Like
local nextPosition
	
while mobHum.Health > 0 do
	nextPosition = "placeholder"
	local path = pathFindingService:CreatePath()
	task.wait()
end
while mobHum.Health > 0 do
	local nextPosition = "placeholder"
	local path = pathFindingService:CreatePath()
	task.wait()
end

(Im just so lazy to do the explanation sorry but if isnt working i try to figurate out)

1 Like