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.

1 comment:

Unknown said...

Why not just t[i] = i? It's just case where you want to differentiate insertion index from loop value?

Making an old USB printer support Apple AirPrint using a Raspberry Pi

There are longer tutorials on how to connect a USB printer to a Raspberry Pi and make it accessible via AirPrint but here's the minimal ...