I need to check if a particular string is one of a set of predetermined strings.
Two methods to do it came to my mind: setting up a table to return true on a particular value
local isParticular = {
[string1] = true,
[string2] = true
}
print(isParticular[string1]) -- true
print(isParticular[randomString]) -- nil -> false
Or setting a function to check it with a conditional determination
function isParticular(s)
return s == string1 or s == string2
end
print(isParticular(string1)) -- true
print(isParticular(randomString)) -- false
From what I understand the table method would take the same time for both any of the particular strings and for different strings, while the function call because of short-circuit evaluation will take less time for string1
and more time for string2
and randomString
.
Also, both the function call and the table access are known for causing a little overhead, but maybe the short-circuit evaluation can make the difference (in being slower I think, especially considered I have more than 2 particular strings and that most of the times the string won't match any of them).
So what method should I use?
A hash-table lookup would outperform your functional lookup for a large dataset. So, go with the first method:
local isParticular = {
string1 = true,
string2 = true
}
print(isParticular[string1]) -- true
print(isParticular[randomString]) -- nil -> false