Battle of the Loops: Luau Edition

Stephen
2 min readJan 2, 2020

A while back, I wrote an article titled Battle of the Loops. In the article, I argued that using “pairs” is always preferred over “ipairs,” and that a classic numeric loop is always faster than the other two.

Since the introduction of Roblox’s new Lua interpreter (Luau), the game has changed significantly. In many ways, the new interpreter has eliminated any reason to fight over which is faster. To sum everything up quickly, all three methods of looping (pairs, ipairs, numeric) are comparable in speed.

To keep this short, here are some general concepts to be aware of:

  • Do not use one type of loop over another for the sake of optimization, because they are all comparable in speed. The differences are too minuscule.
  • Use “ipairs” instead of “pairs” to guarantee the order of each item in the loop is consistent with the index. The “pairs” iterator does not guarantee order.
  • A numeric “for” loop is technically faster…if it doesn’t need to do anything. As soon as you need to start accessing a table with the loop’s counter index, then “ipairs” becomes the faster alternative. Again, the difference is very small (~ 2% difference in performance).
  • As stated in the previous article, using “next” instead of “pairs” has no performance difference and is only a matter of personal preference.

My personal opinions on the matter:

  • When iterating through a table, I will use “ipairs” if possible, otherwise I will use “pairs”.
  • I will never create mixed tables. These are terrible in design and can introduce hard-to-find bugs.
  • Due to the minuscule difference in performance, readability becomes the top priority regarding which looping method to use. In my opinion, using “pairs” or “ipairs” is always more readable than using a numeric loop to iterate through a table.

--

--