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

for i=1,#mytbl do

Practice As Follows

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


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.