I have read that the use of ipairs is slow compared to a for loop, should I change my programming habit? I'll be using lua 5.2 one day, currently 5.1.
My arrays are approximately 1000 items at most.
local mytbl = { 'a','b','c','e'}
for i,v in ipairs(mytbl) do
print(i,v)
end
for i=1,#mytbl do
print(i,mytbl[i])
end
pairs() returns key-value pairs and is mostly used for associative tables. key order is unspecified. ipairs() returns index-value pairs and is mostly used for numeric tables. Non numeric keys in an array are ignored, while the index order is deterministic (in numeric order).
Did you mean to say ipairs is faster than pairs? As for OP's question, ipairs is equivalent to a numerical loop, making it faster when iterating over large ordered arrays. pairs is used to iterate over tables that aren't arrays or are unordered.
pairs must be used for dictionaries or arrays with gaps. The only “error” you could have with pairs is that the order is not guaranteed. With ipairs it goes through the array in order, hence needing to be an array with no gaps.
ipairs(table) The ipairs() function will allow iteration over index-value pairs. These are key-value pairs where the keys are indices into an array. The order in which elements are returned is guaranteed to be in the numeric order of the indices, and non-integer keys are simply skipped.
http://springrts.com/wiki/Lua_Performance#TEST_9:_for-loops
pairs: 3.078 (217%)
ipairs: 3.344 (236%)
for i=1,x do: 1.422 (100%)
for i=1,#atable do 1.422 (100%)
for i=1,atable_length do: 1.562 (110%)
Note, however, that using a numerical for
loop only works if you're iterating over tables with sequential numeric indices - if you're using hash keys for your tables, or sparse tables, then you'll need to use some form of pairs()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With