So when cycling through a table or workspace or whatever what I usually see done is for i,v in pairs(table). I also use that a lot in my scripts but I was wondering, if the table was super large, say workspace:GetDescendants(), wouldnt that cause preformance issues since it is just cycling through hundreds of objects at the same time.
Well there’s not really another way without a for loop. Pairs only runs once itself, but it would be a little faster with a numeric for loop (for i = 1, #t)
The lag only depends on what you do inside of the loop.
A for loop (such as pairs or ipairs) in itself is not inefficient at all. It honestly depends on what you’re doing inside the loop and how often.
As you mentioned before you use Workspace:GetDescendants(). Now this shouldn’t really be an issue if your place has like 100 parts or what not (Assuming you aren’t doing no crazy calculations). However, if you have like 10000+ parts (Possibly with meshes, billboards, particles, effects, etc) then you could see some performance issues depending on how many times you’re looping through it.
I understand it might be easy just to loop through everything in workspace but why not instead have stuff you want to loop through in its own folder.
Example: Instead of looping through the entire workspace to connect a touch function to “kill bricks”, you could simply create a folder and store your kill bricks in there. Then you can simply loop through that folder.
You can also use CollectionService and tag items, etc:
Well, pairs, numerical for loop, next are all situational and can be used in different scenarios. In terms of speed, they’re quite similar. I’m not sure where I heard it, but ‘ipairs
’ is quicker because of the Luau Update, followed by pairs
and numerical for loop ? Or have I got it wrong?
Pairs returns a callback function that is used to return values and pass them to the arguments you pass to the for loop (e.g. i
and v
). Usually this is used for iteration, but could theoretically be used for other things…
I’m not sure how else you could go through all the descendants of the workspace; if you need to iterate through all the descendants, then you have no choice. If you have a way to reference an Instance directly, do that instead.
Oh thanks but, I wasn’t using workspace:GetDescendants() that was just an extreme example, I was just curious whether I should stop using pairs.
workspace:GetDescendants()
returns an array, I would suggest using ipairs in this case, as ipairs is designed for arrays, pairs is mainly used in dictionaries.
If the loop makes your game lag, I would add a small wait() inside it.