## Wednesday, April 03, 2013

### Performance of array creation in Lua

The Lua 5.1 Optimization Notes say: "Short inline expressions can be faster than function calls. t[#t+1] = 0 is faster than table.insert(t, 0)." But the question is what's the fastest way to insert a number of items into a table (as an array).

Naive base test case (naive.lua): using Lua 5.2 is takes (average of 5 runs) 1718ms.

Make table.insert into a local (local.lua): using Lua 5.2 is takes (average of 5 runs) 1408ms (vs. base 82.0%).

Following the advice from the optimization tips (optimized.lua): using Lua 5.2 is takes (average of 5 runs) 1180ms (vs. base 68.7%)

Using a simple implementation with a counter (counter.lua): using Lua 5.2 is takes (average of 5 runs) 193ms (vs. base 11.2%)

So, the rather simplistic implementation with a counter is almost 9x faster than the naive implementation and it's 6x faster than the advice from the optimization page.

Moral: it pays to measure.

Switching to the most recent LuaJIT gives the following times: naive base case: 845ms, table.insert is local: 836ms, following the advice: 837ms, simple implementation with counter: 55ms. So, the simple implementation is 15x faster than any other implementation.

If you enjoyed this blog post, you might enjoy my travel book for people interested in science and technology: The Geek Atlas. Signed copies of The Geek Atlas are available.

<$BlogCommentBody$>

<$BlogCommentDateTime$> <$BlogCommentDeleteIcon$>

<$BlogBacklinkControl$> <$BlogBacklinkTitle$> <$BlogBacklinkDeleteIcon$>
<$BlogBacklinkSnippet$>