Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use ipairs or a for loop

Tags:

lua

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
like image 821
topskip Avatar asked Jan 21 '12 17:01

topskip


People also ask

Should I use pairs or Ipairs?

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

Is Ipairs faster than pairs Roblox?

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.

What's the difference between pairs and Ipairs Roblox?

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.

What does Ipairs mean in Lua?

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.


1 Answers

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

like image 111
Amber Avatar answered Sep 28 '22 09:09

Amber