lua – 使用“数组样式”表是否比使用“地图样式”表提供更快的读取访问权限?

我正在使用Love2D在Lua中编写游戏.

每个实体显然都有一个x,y位置,它只是一个名为“position”的表,它保存{x,y}(即{10,4}).

到目前为止,我一直在使用数组运算符实现表,所以为了得到x值,我调用位置[1],得到y值我调用位置[2].

但是为了便于阅读,我更愿意调用position.x和position.y.这将涉及以“地图”样式使用表格,如position = {x = 10,y = 4}.

虽然数组查找时间显然必须是O(1),但我担心使用地图样式会产生更糟糕的结果,因为地图往往比简单数组内部复杂一百万倍.

在某种程度上,我怀疑性能差异会很重要,即使它在我的主游戏循环中被称为每分钟一百万次.我只是想更好地理解我用来创建这个游戏的工具.

谢谢!

解决方法

罗伯托等人的 Implementation of Lua 5.0摘录:

Until Lua 4.0,tables were implemented strictly as hash tables: all pairs were
explicitly stored. Lua 5.0 brought a new algorithm to optimize the use of tables
as arrays: it optimizes pairs with integer keys by not storing the keys and storing the values in an actual array. More precisely,in Lua 5.0,tables are implemented as hybrid data structures: they contain a hash part and an array part.

[…]

This hybrid scheme has two advantages. First,access to values with integer keys is faster because no hashing is needed. Second,and more important,the array part takes roughly half the memory it would take if it were stored in the hash part,because the keys are implicit in the array part but explicit in the hash part. As a consequence,if a table is being used as an array,it performs as an array,as long as its integer keys are dense. Moreover,no memory or time penalty is paid for the hash part,because it does not even exist.

所以,是的,如果你使用Lua 5或更高版本,那么只使用表格作为数组,速度和内存应该存在显着差异.

I doubt the performance difference would matter much,even if it’s called a million times a minute in my main game loop.

在得出与性能相关的任何内容之前,最好先进行基准测试,因为这通常是违反直觉的.对于可读性而言,你可能会对表现感到满意 – 但是要以明智的方式这样做.

如果您可以编写辅助函数来获取相同的数据,也许您不必牺牲可读性:

function X(t)
    return t[1]
end

function Y(t)
    return t[2]
end

local pos = { 8,1 }
print(X(pos))

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...