Sometimes I look at code of other people and when they do a for loop with GetChildren(), instead of using ipairs(), which would be the correct loop for arrays, they use pairs(), which is meant to work with dictionaries. Why is that?
Some people use pairs()
with GetChildren()
because it works in both cases, but it’s not as efficient or predictable as ipairs()
. pairs()
loops over all key-value pairs in a table, regardless of whether it’s an array or dictionary, while ipairs()
ensures it iterates over array elements in numerical order. In most cases, GetChildren()
returns a sequential array, so ipairs()
is more appropriate and guarantees ordered traversal, while pairs()
might be used out of habit or misunderstanding, despite being less optimal for arrays.
TLDR; People use pairs()
out of habit or misunderstanding, even when ipairs()
is better for arrays.
Hope this helps!
Hilariously enough, Luau has a feature called generalised iteration, and its faster than pairs or ipairs could even dream of.
for i, v in {} do
end
it is basically just pairs under the hood (not exactly technical wise), but you get a performance boost from not constantly calling a function every iteration.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.