Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table access efficiency

I have a question about accessing data in a Lua table.
Say, there is a large Lua table like following:

 tbl = {
         {
           blockIdx = 5,
           key1 = "val1",
           key2 = "val2",
           ...
         },
         {
           blockIdx = 30,
           key1 = "val11",
           key2 = "val12",
           ...
         },
         {
           blockIdx = 83,
           key1 = "val21",
           key2 = "val22",
           ...
         },
         ...
       }

And now I want to find one of the block that blockIdx is , for example, 38.
So normally, I would like to use for to find the block:

for k,v in pairs(tbl) do
     if v.blockIdx == 38 then
        blahFunction(v)
     end
end

But I don't think it is a good idea especially for large table.
So I modify the table a bit:

 tbl = {
         [5] = { 
           key1 = "val1",
           key2 = "val2",
           ...
         },
         [30] = {
           key1 = "val11",
           key2 = "val12",
           ...
         },
         [83] = {
           key1 = "val21",
           key2 = "val22",
           ...
         },
         ...
       }

Then I can easily access my block with one line:

blahFunction(tbl[38])

So my question is, is there any performance different between two method?
Maybe doing tbl[38] actually did a for loop inside Lua?
Or just like an array in C/C++ we can direct access memory using [ ] without for loop,
witch obviously has much better performance.

like image 908
Wayne Dimart Avatar asked Apr 24 '14 02:04

Wayne Dimart


1 Answers

The performance is different, the second method is more efficient.

Internally, a Lua table contains an array part and a hash part, if the table is a sequence, then the sequence part is implemented by the array part. But the table in your second example is not a sequence, it's probably implemented by the hash part. The performance in this case is not like accessing arrays in C/C++, but like accessing a hash, which is still pretty fast.

So in conclusion, the second piece of code is faster, because it doesn't iterate through the elements like in your first example.

like image 52
Yu Hao Avatar answered Oct 29 '22 13:10

Yu Hao