桌子搜索与字符串的性能。
假设我想存储一些字母数字数据。我可以使用表:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑这样做:
然后要测试字符串
s
是否在t
中,只需执行以下操作Consider doing this:
Then to test if a string
s
is int
, simply do我在löve[love2d]的两个框架之间做类似的事情。
我可以说,没有基准测试:它足够快
(帧仅使用许多可绘制的对象减小)
此外,我想将表函数添加到表
t
作为方法......
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......check it out or change this in...
https://www.lua.org/demo.html
...to figure out how it works.