Should I use ipairs or a for loop

24.2k Views Asked by At

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
1

There are 1 best solutions below

8
Amber On BEST ANSWER

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().