Home > database >  Performance of Table Search vs. string.find in Lua
Performance of Table Search vs. string.find in Lua

Time:03-30

Let's say that I want to store some alphanumeric data. I can either use a table:

t = { "a", "b", "c" }

or a string:

s = "abc"

When I want to test if 'b' is in my data set, I can test the table by saying:

function findInTable(table, element)
    for i, v in ipairs(table) do
        if v == element then return true end
    end
    return false
end

if findInTable(t, "b") then
--do stuff

or I can test the string by saying:

if s:find("b") then
--do stuff

Which of these methods is faster? I imagine that string.find is essentially doing the same thing as my findInTable function. I need to check data in this way on every draw for a game, so performance is critical. A lot of my data is being extracted from text files and it's easier to keep it in string format rather than using commas or some such as delimiters to organize it into table values.

CodePudding user response:

I do similar things between two frames in LÖVE [love2d].
And without benchmarking it i can say: Its fast enough
( Frames decreases with many drawable objects only )
Moreover i would like to add the table functions to the table t as methods...

t = setmetatable({"a", "b", "c"}, {__index = table})
print(t[t:concat():find("b")])
-- Output: b
-- False Output: nil
-- And nil never happens if...
print(t[t:concat():find("d")] or t[#t])
-- Output: c
-- ..fallback to a default with: or

...check it out or change this in...
https://www.lua.org/demo.html
...to figure out how it works.

CodePudding user response:

Consider doing this:

t = { ["a"]=true, ["b"]=true, ["c"]=true }

Then to test if a string s is in t, simply do

if t[s] then ...
  • Related