Using in pairs for for loop or for loop number of child?

when to use this

for i = 1,#build do
build[i]
end
--or 
for i,j in pairs(build) do
j
end

are they practically the same thing or theres some difference? which is performant wise?

They’re technically the same thing.

for i = 1,#build do
    build[i] -- build [the number of current child]
end

for i,j in pairs(build) do
j -- j is the current child and i is the current number of the current child
end
1 Like

You should use ipairs to iterate over an array of items. If it has hashed items, use pairs. These are optimized for such cases.

The only time I use a numeric for loop to iterate over an array is if I am trying to iterate over it in a different order (e.g. in reverse or more than one item at a time).

2 Likes

Here you are just going through a for i loop:

Here we are having a for i,v loop for now it does the same thing but in the second loop we have both object and the number and is running through a table while the first is going through a series of numbers

In your example they are same

Both are doing the exact same work so no major performance differences

1 Like

(Sorry for being off-topic) Funny enough I got into a conversation yesterday concerning pairs vs ipairs when it comes to looping through an array. It’s not really about optimization, at least from what I know there is nothing special happening internally making ipairs faster when looping solely through an array. The best reason to use ipairs over pairs with arrays is due to the fact that it is never guaranteed that it will loop through it in order. It is not guaranteed because:

  • First, there can be a human change in luau’s implementation disallowing pairs from looping in order, this change might happen for example for optimization reasons, looping randomly might be better than in order.

  • Second, a sudden automatic change. Lua performs some action called rehashing (here) on a table when you insert/remove something from that table. For some odd reason, there is a possibility when it does this, array indices become keys, thus the array part is transfered to the hash part, making it looped randomly. This doesn’t happen with ipairs because it apparently also keeps an internal counter, so the size of array part is clear when rehashing. I wish I could link the conversation but it’s a discord link.

tl;dr, ipairs is the correct way to loop through an array, because it has no risks of not looping in order.

2 Likes