Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top