What are pairs and ipairs for anyway?

One person whom I respect did an investigation about two years ago and came to the conclusion that the pairs iterator slows down the cycle. At the same time, if you just don’t use the iterator (write in Collection instead of in pairs(Collection)), nothing will change. Why Do I need to use (i)pairs?

image
Exponentiation. 10,000 iterations. Average time. The values are multiplied by 1000 times

Pairs and ipairs just indicute tell Roblox what kind of table is coming: key - value or index - value. Not using either keywords is a fairly new feature in luau; in the past, you had to use either.

1 Like

pairs works with dictionaries, expecting a key-value pair (index-value pairs as well), i.e {hi = 2}
In contrast, ipairs expects only index-value pairs, ie {"hi"} (which is the same as {[1] = "hi"}

By the way, the ‘i’ in ipairs represent index for index pairs.
The reason ipairs is faster is because it expects only index-value pairs whilst pairs expects either which forces it to decide whether the table is in key-value pairs or index-value pairs.

2 Likes

ipairs is for iteration on tables with integer only keys which is why it’s faster

pairs is for iterating on any type of table and they key value can be string or integer which is why its slower

in Luau you don’t have to use pairs or ipairs or next you can just use the table name directly

for key, value in table do

end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.