您如何在Lua中预先调整数组大小? [英] How do you pre-size an array in Lua?

查看:663
本文介绍了您如何在Lua中预先调整数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Lua程序,它似乎比应该的要慢.我怀疑问题在于我一次将值添加到一个关联数组中,并且表每次必须分配新的内存.

I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time.

似乎确实有一个table.setn函数,但是在Lua 5.1.3下失败了:

There did seem to be a table.setn function, but it fails under Lua 5.1.3:

stdin:1: 'setn' is obsolete
stack traceback:
        [C]: in function 'setn'
        stdin:1: in main chunk
        [C]: ?

我从Google搜索中收集到的信息是,该功能在Lua 5.1中已被弃用,但是我找不到什么(如果有的话)替代了该功能.

I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.

您知道如何在Lua中对表进行预大小吗?

Do you know how to pre-size a table in Lua?

或者,当您将对象添加到表中时,还有其他方法可以避免内存分配吗?

Alternatively, is there some other way to avoid memory allocation when you add an object to a table?

推荐答案

让我更加关注您的问题:

Let me focus more on your question:

将值添加到关联数组 一次一个

adding values to an associative array one at a time

Lua中的表是关联的,但是以数组形式(1..N)使用它们得到了优化.他们内部有两张脸.

Tables in Lua are associative, but using them in an array form (1..N) is optimized. They have double faces, internally.

所以.如果您确实是在关联地添加值,请遵循上述规则.

So.. If you indeed are adding values associatively, follow the rules above.

如果使用索引1..N,则可以通过将t [100000] =设置为某值来强制一次调整大小.这应该一直起作用,直到在Lua源中指定的优化数组大小的限制为止(2 ^ 26 = 67108864).之后,一切都是关联的.

If you are using indices 1..N, you can force a one-time size readjust by setting t[100000]= something. This should work until the limit of optimized array size, specified within Lua sources (2^26 = 67108864). After that, everything is associative.

p.s.旧的"setn"方法仅处理数组部分,因此对于关联用法没有用(忽略这些答案).

p.s. The old 'setn' method handled the array part only, so it's no use for associative usage (ignore those answers).

p.p.s.您是否研究了使Lua保持高性能的一般技巧?即知道表的创建,而不是重用表而不是创建新表,使用'local print = print'等避免全局访问.

p.p.s. Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.

这篇关于您如何在Lua中预先调整数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆