Can for i,v loops cause lag?

image

For my new game, I am making a script which allows admins to delete other player’s builds. The problem is, builds are meant to save when a player leaves/joins the game, and I need to delete the build from the player’s data save too.

Player builds are currently saved to a datastore. Each build has their name, position, and orientation value saved. A player can place a maximum of about 50,000 builds before reaching the datastore limit.

My first idea to remove the build from their data saves is to loop through their saved builds, and find the same type of build that has the same position and orientation as the object I’m deleting. However, if a player has 50,000 builds placed, I would assume that it would cause lag

Is there a more efficient way to accomplish what I am doing? Will the loop cause lag if (possibly) looping through 50,000 different builds?

3 Likes

Loops don’t lag. The lag is dependent on what is inside the loop.

Ok. Do you think there is a more efficient way to remove the build from the player’s datastore?

Could each build be given an ID and could it be deleted by that ID instead? You could then save a dictionary in the DataStore and remove the key directly instead of looping through it.

This is a good idea, but there’s a few issues. I want to keep the building cap to the highest possible, so a player can build tens of thousands of builds. This would increase the amount of storage being used

I tried my method, and the loop does lag. Here is what I have:

			for i,v in pairs(PlayerBuilds) do -- loop through player's builds
				local BuildPosition = Vector3.new(table.unpack(v.Position)) -- v's position property
				local BuildOrientation = Vector3.new(table.unpack(v.Orientation)) -- v's orientation property
				if BuildPosition == build.Position) and BuildOrientation == build.Orientation then -- if the position and orientation of the selected part and v are the same, then
					table.remove(PlayerBuilds, i) -- remove the build from the PlayerBuildsTable
					MyDataStore:SetAsync(Key, http:JSONEncode(PlayerBuilds)) -- Save the new builds table
					break -- break the loop, so it won't delete multiple parts which are inside of each other
				end
			end

Make sure you’re using Profile Service btw. It’ll stop data loss in its tracks. You may have gotten no reports for data loss, but it happens when your game gets a lot of traffic eventually.

Depending on what is inside of the loop, the loop may cause lag.

This highly depends on how much stuff you have inside the table you’re looping through with a huge number of code inside of it. If you were to make an explosion system where it damages ranged blocks, you’d do workspace:GetPartBoundsInRaidus(pos,range).

it depends on the client’s pc specs, obviously, but also how many will be running at once and what is inside of them.