Variable Declarations inside a loop

Is there any difference in performance and memory usage between declaring a local variable outside the loop first then changing the value of it inside of the loop to declaring a local variable inside of a loop

variable outside of the loop

local GhostTag, PlayerChar, BreathingSound, Index, HumanoidRootPart
		
		
		--- Teleports all the ghosts
		for i,player in pairs(ghosts) do
			
		 	GhostTag = Instance.new("StringValue")
			GhostTag.Name = "ghost"
			GhostTag.Value = player.Name
			GhostTag.Parent = GameInfo.Players
			
			
			PlayerChar = player.Character
			if not PlayerChar then
				continue
			end
			
			BreathingSound = ServerStorage.Assets.Audios.Breathing:Clone()
			BreathingSound.Parent = PlayerChar:WaitForChild("Head")
			
			PlayerChar.GhostScript.Disabled = false
			HumanoidRootPart = PlayerChar:WaitForChild("HumanoidRootPart")
			
			Index = i % #GhostSpawns
			
			
			player.playerinfo.IsGhost.Value = true
			
			if HumanoidRootPart ~= nil then
				HumanoidRootPart.Position = GhostSpawns[Index].Position
			end
			
		end

variable inside of a loop

		
		
		--- Teleports all the ghosts
		for i,player in pairs(ghosts) do
			
		 	local GhostTag = Instance.new("StringValue")
			GhostTag.Name = "ghost"
			GhostTag.Value = player.Name
			GhostTag.Parent = GameInfo.Players
			
			
			local PlayerChar = player.Character
			if not PlayerChar then
				continue
			end
			
			local BreathingSound = ServerStorage.Assets.Audios.Breathing:Clone()
			BreathingSound.Parent = PlayerChar:WaitForChild("Head")
			
			PlayerChar.GhostScript.Disabled = false
			local HumanoidRootPart = PlayerChar:WaitForChild("HumanoidRootPart")
			
			local Index = i % #GhostSpawns
			
			
			player.playerinfo.IsGhost.Value = true
			
			if HumanoidRootPart ~= nil then
				HumanoidRootPart.Position = GhostSpawns[Index].Position
			end
			
		end
1 Like

There is a lot of factors in play here, but in this case you’re just making it unreadable and also exposing variables that I think you’re only using inside the loop.

Bottom line: Only do this unless you need the last elements in the for loop to be used after the loop, otherwise in your case, just go with declaring and initializing variables inside the loop itself (method 2)

2 Likes