Need help with optimizing code

Anyone know how I can optimize this render distance code so it doesn’t constantly lag? It’s ran every two seconds and I get a small but noticeable lag spike.

-- services
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- vars
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local RenderCache = ReplicatedStorage:WaitForChild("Cache")

local Rendering = {
	Enabled = false, -- pls only turn this off when testing and if you wanna lag lol
	RenderDistance = 200,
	ToRender = {
		workspace,
	}, -- Keep it as workspace but feel free to add on
	
	Objects = {} -- don't mess with this
}

table.insert(Rendering.ToRender, RenderCache)

function Rendering:Render()
	task.wait(0.2)
	if self.Enabled then
		local GetToRender = self:GetToRender() 
		for _, Object in pairs(GetToRender) do
			if Object then
				local GetPartToRender = self:GetPartToRender(Object)
				if GetPartToRender then
					local Distance = (GetPartToRender.CFrame.p - Character.HumanoidRootPart.CFrame.p).Magnitude
					if Distance < self.RenderDistance then
						Object.Parent = workspace
					else
						Object.Parent = RenderCache
					end
				else
					Object.Parent = RenderCache
				end
			end
		end
	end
end

function Rendering:GetToRender()
	local Objects = self.Objects
	local NewObjects = {}
	if #Objects < 1 then
		for _, Service in pairs(self.ToRender) do
			for _, Object in pairs(Service:GetChildren()) do
				if Object.Name ~= "Terrain" and (Object:IsA("Model") or Object:IsA("Folder") or Object:IsA("BasePart")) then
					table.insert(Objects, Object)
				end
			end
		end
		return Objects
	else
		for _, Object in pairs(Objects) do
			if Object.Name ~= "Terrain" and (Object:IsA("Model") or Object:IsA("Folder") or Object:IsA("BasePart")) then
				table.insert(NewObjects, Object)
			end
		end
		return NewObjects
	end
end


function Rendering:GetPartToRender(Object)
	local CloestPart
	if not Object:IsA("BasePart") and Object.Name ~= "Terrain" then
		local Part = Object:FindFirstChildWhichIsA("BasePart", true)
		if Part then
			if not CloestPart then
				CloestPart = Part
			else
				if Part.CFrame.p.Magnitude < CloestPart.CFrame.p.Magnitude then
					CloestPart = Part
				end
			end
		end
	elseif Object.Name ~= "Terrain" then
		CloestPart = Object
	end
	return CloestPart
end

return Rendering

1 Like
  1. Why not just use streaming enabled?
  2. You should probably benchmark (time) each function individually to help pin down the problem, although it could just be all the reparenting.
3 Likes