RunTime service or While true

I’ve always wondered which of the 2 is better, I know that by using the runtime service everything should be more stable, but doing some tests I saw that it actually consumes more memory, can anyone give me an opinion on this? I attach a piece of code and some screen shots

while task.wait()

local position = script.Parent.PrimaryPart.Position.Y
local maxPosition = position + 5
local flag = false

while task.wait() do
	if script.Parent.PrimaryPart.Position.y < maxPosition and flag == false then
		script.Parent.PrimaryPart.CFrame = script.Parent.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0,0.01,0) * CFrame.new(0,0.1,0)
	else
		flag = true
		script.Parent.PrimaryPart.CFrame = script.Parent.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0,0.01,0) * CFrame.new(0, -0.1, 0)
		if  script.Parent.PrimaryPart.Position.y <= position then
			flag = false
		end
	end
end

RunTimeService

local position = script.Parent.PrimaryPart.Position.Y
local maxPosition = position + 5
local movingUp = true

game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
	if script.Parent.PrimaryPart.Position.Y < maxPosition and movingUp then
		script.Parent.PrimaryPart.CFrame = script.Parent.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.01, 0) * CFrame.new(0, 0.1, 0)
	else
		movingUp = false
		script.Parent.PrimaryPart.CFrame = script.Parent.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0, 0.01, 0) * CFrame.new(0, -0.1, 0)
		if script.Parent.PrimaryPart.Position.Y <= position then
			movingUp = true
		end
	end
end)

This is with RunTime Script

This is with While task.wait()

1 Like

The .RenderStepped signal is actually quite similar to task.wait(). They do have their differences however. For example, a while loop while not iterate again until its current iteration has been completed. Another example would be that if an error occurred within the loop, the loop would stop completely (unless the code inside resided within a separate thread)

As for .RenderStepped. The function will fire every frame without waiting for the current function to complete, hence it runs every frame regardless of if the current function is being held up. Additionally, if an error occurred within the function, it will not stop the signal from continuing to fire another, hence it’ll work until the signal has been disconnected.

From the information you’ve provided, the memory usage does not come from the code you’ve provided. There isn’t much declaration of variables, nor does it seem that any instances are being created. The large memory is most likely due to you benchmarking within studio alongside external roblox scripts which may fluctuate the memory.


Both of the methods listed above are useful, but for your case I’d suggest a while loop as such:

while true do
	-- ...
	
	task.wait()
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.