在循环内还是循环外声明局部更好? [英] Is it better to declare a local inside or outside a loop?
问题描述
我曾经这样做:
do
local a
for i=1,1000000 do
a = <some expression>
<...> --do something with a
end
end
代替
for i=1,1000000 do
local a = <some expression>
<...> --do something with a
end
我的理由是,创建1000000次局部变量的效率要比仅创建一次并在每次迭代中重用的效率低.
My reasoning is that creating a local variable 1000000 times is less efficient than creating it just once and reuse it on each iteration.
我的问题是:这是真的还是我遗漏了另一个技术细节?我之所以问是因为我没有看到任何人这样做,但是不确定原因是因为优势太小还是因为事实更糟.更好的意思是使用更少的内存并运行得更快.
My question is: is this true or there is another technical detail I am missing? I am asking because I don't see anyone doing this but not sure if the reason is because the advantage is too small or because it is in fact worse. By better I mean using less memory and running faster.
推荐答案
像任何性能问题一样,请先进行测量.在Unix系统中,您可以使用时间:
Like any performance question, measure first. In a unix system you can use time:
time lua -e 'local a; for i=1,100000000 do a = i * 3 end'
time lua -e 'for i=1,100000000 do local a = i * 3 end'
输出:
real 0m2.320s
user 0m2.315s
sys 0m0.004s
real 0m2.247s
user 0m2.246s
sys 0m0.000s
在Lua中,更本地的版本似乎要快一小部分,因为它不会将 a
初始化为nil.但是,这不是使用它的原因,使用最本地的范围是因为它更具可读性(这在所有语言中都是很好的样式:请参阅此问题以询问C , C#)
The more local version appears to be a small percentage faster in Lua, since it does not initialize a
to nil. However, that is no reason to use it, use the most local scope because it it is more readable (this is good style in all languages: see this question asked for C,
Java, and C#)
如果要重用表而不是在循环中创建表,则可能会有更大的性能差异.无论如何,请尽可能测量并支持可读性.
If you are reusing a table instead of creating it in the loop then there is likely a more significant performance difference. In any case, measure and favour readability whenever you can.
这篇关于在循环内还是循环外声明局部更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!