Cyan
Cyan

Reputation: 135

Lua tables: performance hit for starting array indexing at 0?

I'm porting FFT code from Java to Lua, and I'm starting to worry a bit about the fact that in Lua the array part of a table starts indexing at 1 while in Java array indexing starts at 0.

For the input array this causes no problem because the Java code is set up to handle the possibility that the data under consideration is not located at the start of the array. However, all of the working arrays internal to the code are assumed to starting indexing at 0. I know that the code will work as written -- Lua tables are awesome like that -- but I have no sense at all about the performance hit I might incur by having the "0" element of the array going into the hash table part of the underlying C structure (or indeed, if that is what will happen).

My question: is this something worth worrying about? Should I be planning to profile and hand-optimize the code? (The code will eventually be used to transform many relatively small (> 100 time points) signals of varying lengths not known in advance.)

Upvotes: 2

Views: 1600

Answers (2)

kikito
kikito

Reputation: 52641

I think the correct answer in this case is changing the algorithm so that everything is indexed with 1. And consider that part of the conversion.

Your FFT will be less surprising to another Lua user (like me), given that all "array-like" tables are indexed by one.

It might not be as stressful as you might think, given the way numeric loops are structured in Lua (where the "start" and the "end" are "inclusive"). You would be exchanging this:

for i=0,#array-1 do
  ... (do stuff with i)
end

By this:

for i=1,#array do
  ... (do stuff with i)
end

The non-numeric loops would remain unchanged (except that you will be able to use ipairs too, if you so desire).

Upvotes: 0

wasylszujski
wasylszujski

Reputation: 146

I have made small, probably not that reliable, test:

local arr = {}
for i=0,10000000 do
  arr[i] = i*2
end

for k, v in pairs(arr) do
  arr[k] = v*v
end

And similar version with 1 as the first index. On my system:

$ time lua example0.lua
real  2.003s

$ time lua example1.lua
real  2.014s

I was also interested how table.insert will perform

for i=1,10000000 do
  table.insert(arr, 2*i)
...

and, suprisingly

$ time lua example2.lua
real 6.012s

Results: Of course, it depends on what system you're running it, probably also whic lua version, but it seems that it makes little to no difference between zero-start and one-start. Bigger difference is caused by the way you insert things to array.

Upvotes: 3

Related Questions