How can I get my code to run faster and smoother

Hello.
I’m making a virtual custom CPU. I’m making a screen-draw routine and the code below is the code I use to draw data to a virtual screen. However, when I execute this code, my instance of Studio freezes for a bit before the screen updates due to the amount of looping taking place. I’d like to know how I could at least reduce this lag to a point where this loop could run non-stop from a function and my game could remain at playable framerates.

Any help would be appreciated. Thanks.

This is the code:

for i = 1,2500 do
		if memory[i] ~= lastbuffer[i] then
			if game.StarterGui.ScreenGui.Frame:FindFirstChild(i) then
				game.StarterGui.ScreenGui.Frame:FindFirstChild(i):Destroy()
			end
			local pixel = memory[i]
			if pixel then
				local frame = Instance.new("Frame",game.StarterGui.ScreenGui.Frame)
				frame.BackgroundColor3 = Color3.new(1, 1, 1)
				frame.BorderSizePixel = 0
				local c = ""
				for i = 1,4-tonumber(#tostring(#game.StarterGui.ScreenGui.Frame:GetChildren()-1)) do
					c = c.."0"
				end
				c = c..#game.StarterGui.ScreenGui.Frame:GetChildren()-1
				frame.Name = c
			else
				local frame = Instance.new("Frame",game.StarterGui.ScreenGui.Frame)
				frame.BackgroundColor3 = Color3.new(0, 0, 0)
				frame.BorderSizePixel = 0
				local c = ""
				for i = 1,4-tonumber(#tostring(#game.StarterGui.ScreenGui.Frame:GetChildren()-1)) do
					c = c.."0"
				end
				c = c..#game.StarterGui.ScreenGui.Frame:GetChildren()-1
				frame.Name = c
			end
		else
			if not game.StarterGui.ScreenGui.Frame:FindFirstChild(i) then
				local pixel = memory[i]
				if pixel then
					local frame = Instance.new("Frame",game.StarterGui.ScreenGui.Frame)
					frame.BackgroundColor3 = Color3.new(1, 1, 1)
					frame.BorderSizePixel = 0
					local c = ""
					for i = 1,4-tonumber(#tostring(#game.StarterGui.ScreenGui.Frame:GetChildren()-1)) do
						c = c.."0"
					end
					c = c..#game.StarterGui.ScreenGui.Frame:GetChildren()-1
					frame.Name = c
				else
					local frame = Instance.new("Frame",game.StarterGui.ScreenGui.Frame)
					frame.BackgroundColor3 = Color3.new(0, 0, 0)
					frame.BorderSizePixel = 0
					local c = ""
					for i = 1,4-tonumber(#tostring(#game.StarterGui.ScreenGui.Frame:GetChildren()-1)) do
						c = c.."0"
					end
					c = c..#game.StarterGui.ScreenGui.Frame:GetChildren()-1
					frame.Name = c
				end
			end
		end
	end
	lastbuffer = memory

You could manually sleep the current thread with task.wait() for example very 250 loop iterations. This would spread the process over multiple ticks which would fix the freezing.

if i % 250 == 0 then task.wait() end

Thanks for this. It works in my code.

1 Like