Should I use ipairs or a for loop

Spread the love

Question Description

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

Practice As Follows

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

Tags

Not what you're looking for? Browse other questions tagged

You may be interested in these books.

(paid link)

As an Amazon Associate I earn from qualifying purchases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.