Which one is better practice? Using a loop to find an index, or using square brackets?

Which one is more efficent?

local List = {}

local function findPlayer(Character)
      return List[Character]
end 

or


local List = {}

local function findPlayer(Character)
      for Char, Value in pairs(List) do
            if Char == Character then
                  return Value
            end
     end
end

1 Like

Always the first one. Your first example has a time complexity of O(1) since you are directly fetching a value from a table.

Your second example has a time complexity of O(n), where ‘n’ refers to the number of items you have inside your table. Meaning if your table has 10 items, you may need to iterate over every single one of those 10 items to find the Character, whereas in the first example you’re getting it straight away through accessing the value in the table with the provided key.

2 Likes

To put what YAYAYGPPR said in simpler terms, the first one is faster. Why? Because you are not searching through a whole table.

2 Likes

Huh, wow thats interesting. I was always under the impression that both are similar because they both search through every element to confirm. Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.