Performance considerations around sandbox placement system

Hello,

I am working on a in depth sandbox placement system where players can build.
The problem I am having is perfomance.

To execute this code it takes ~1 second when 300 models are placed out.

game:GetService("Players").PlayerAdded:Connect(function(Player)
	while true do
		wait(15)
		Player.leaderstats["Day"].Value += 1
		for i,v in ipairs(workspace.Plot.Folder:GetChildren()) do
			Player.leaderstats["Money ($)"].Value += v.Income.Value
			Player.leaderstats["Money ($)"].Value -= v.Upkeep.Value
			Player.leaderstats["Population"].Value += (v.Population.Value - Random.new():NextInteger(0,3))
			Player["MonthIncome"].Value += v.Income.Value
			Player["MonthExpense"].Value += v.Upkeep.Value
			
		end
		
		if Player.leaderstats["Day"].Value >= 32 then
			game.ReplicatedStorage.Remotes.MonthResult:FireClient(Player, Player["MonthExpense"].Value, Player["MonthIncome"].Value)
			
			Player["MonthIncome"].Value = 0
			Player["MonthExpense"].Value = 0
			Player.leaderstats["Day"].Value = 1
			
			print("Profit:", (Player["MonthIncome"].Value - Player["MonthExpense"].Value))
		end
	end
end)

How would I improve this to not be as performance heavy.

Thanks in advance.

2 Likes

Keep track of an overall income for each player - possibly using a dictionary. Same thing with the other statistics. You only want to re-compute them when new objects are being placed/removed. That way in your infinite loop, you can access the values directly from the dictionary in constant time. This will help increase performance dramatically from your current implementation

2 Likes