gpt4 book ai didi

lua - 使用 "array style"表是否比使用 "map style"表提供更快的读取访问?

转载 作者:行者123 更新时间:2023-12-01 09:52:34 25 4
gpt4 key购买 nike

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

每个实体显然都有一个 x,y 位置,它只是一个名为“位置”的表,其中包含 {x, y}(即 {10, 4})。

到目前为止,我一直在使用数组运算符实现表格,因此要获取 x 值,我会调用 position[1],而要获取 y 值,我会调用 position[2]。

但是,为了可读性,我更愿意调用 position.x 和 position.y。这将涉及以“ map ”样式使用表格,例如 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))

关于lua - 使用 "array style"表是否比使用 "map style"表提供更快的读取访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com