桌子搜索与字符串的性能。

发布于 2025-01-18 00:17:37 字数 602 浏览 0 评论 0原文

假设我想存储一些字母数字数据。我可以使用表:

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

或字符串:

s = "abc"

当我想测试“b”是否在我的数据集中时,我可以通过以下方式测试表:

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

或者我可以通过以下方式测试字符串:

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

以下哪种方法更快?我想 string.find 本质上与我的 findInTable 函数做同样的事情。我需要在游戏的每次抽签中以这种方式检查数据,因此性能至关重要。我的很多数据都是从文本文件中提取的,将其保留为字符串格式比使用逗号或某些分隔符(例如分隔符)将其组织为表值更容易。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稍尽春風 2025-01-25 00:17:37

考虑这样做:

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

然后要测试字符串 s 是否在 t 中,只需执行以下操作

if t[s] then ...

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 ...
冰葑 2025-01-25 00:17:37

我在löve[love2d]的两个框架之间做类似的事情。
我可以说,没有基准测试:它足够快
(帧仅使用许多可绘制的对象减小)
此外,我想将表函数添加到表t作为方法...

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

...
https://www.lua.org/demo.html
...弄清楚它是如何工作的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文