Performance of accessing table via reference vs ipairs loop

Viewed 138

I'm modding a game. I'd like to optimize my code if possible for a frequently called function. The function will look into a dictionary table (consisting of estimated 10-100 entries). I'm considering 2 patterns a) direct reference and b) lookup with ipairs:

PATTERN A

tableA = { ["moduleName.propertyName"] = { some stuff } } -- the key is a string with dot inside, hence the quotation marks
result = tableA["moduleName.propertyName"]

PATTERN B

function lookup(type)
   local result
   for i, obj in ipairs(tableB) do
      if obj.type == "moduleName.propertyName" then
          result = obj
          break
      end
   end
   return result
end

***

tableB = { 
    [1] = { 
        type = "moduleName.propertyName", 
        ... some stuff ... 
    } 
}
result = lookup("moduleName.propertyName")

Which pattern should be faster on average? I'd expect the 'native' referencing to be faster (it is certainly much neater), but maybe this is a silly assumption? I'm able to sort (to some extent) tableB in a order of frequency of the lookups whereas (as I understand it) tableA will have in Lua random internal order by default even if I declare the keys in proper order.

1 Answers

A lookup table will always be faster than searching a table every time.

For 100 elements that's one indexing operation compared to up to 100 loop cycles, iterator calls, conditional statements...

It is questionable though if you would experience a difference in your application with so little elements.

So if you build that data structure for this purpose only, go with a look-up table right away.

If you already have this data structure for other purposes and you just want to look something up once, traverse the table with a loop.

If you have this structure already and you need to look values up more than once, build a look up table for that purpose.

Related