(重新)创建堆栈时的性能差异?
之间有性能差异吗
int test;
void Update()
{
test +=2;
}
this:和 this:
void Update()
{
int test;
test +=2;
}
? --
int main()
{
while(true)
Update();
}
我问是因为第二个代码更好读(你不需要在类头声明它),所以如果性能不降低我会使用它。
is there a Performance difference between this:
int test;
void Update()
{
test +=2;
}
and this:
void Update()
{
int test;
test +=2;
}
--
int main()
{
while(true)
Update();
}
I ask because the second Code is better to read (you don't need to declare it at Class headers), so i would use it if the performance is not lower.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个片段之间不太可能存在性能差异,只有对代码进行分析才能可靠地判断,但这里有一个重要的功能差异,您应该考虑。
如果您的
test
变量仅在函数update()
内需要,那么您必须在函数内声明它。这样,变量在函数内的作用域是有限的。此类局部变量的生命周期仅限于它所在的作用域。即在函数体内,直到右大括号}
。如果您确实希望您的
test
变量在函数调用之间保持状态,那么它可以是在函数内部声明的局部静态变量。在函数外部声明
test
使其成为全局变量。并且可以在同一文件中的任何函数中访问它。它也是一个全局变量,它的生命周期可以延长到程序结束。It is highly unlikely that there is a performance difference between the two snippets only profiling your code can tell reliably but there is a important functional difference tha you should consider here.
If your
test
variable is needed only inside the functionupdate()
then you must declare it inside the function. That way the variable has a limited scope inside the function.The lifetime of such a local variable is limited to the scope where it resides.i.e. Within the function body, till the closing brace}
.If at all you want your
test
variable to maintain state across function calls then it can be a local static variable declared inside the function.Declaring
test
outside the function makes it an global variable. And it can be accessible in any function in the same file.Also being a global variable it lifetime extends till end of program.性能差异,不太可能。这很容易测试,但取决于您的编译器。检查输出组件并进行一些基准测试。如果有差异,也可能很小。
然而,存在重大的功能差异。第二个示例实际上毫无用处,因为每次
Update
都会重置test
。为了避免这种情况,您可以将其声明为static int test
,但实际上您已经再次编写了第一个示例。因此,它们是非常不同的东西,但具有相似的性能。
Performance difference, unlikely. This is simple to test, but depends on your compiler. Check the output assembly and do some benchmarking. If there is a difference, it's likely to be tiny.
However, there is a major functional difference. The second example is effectively useless, as
test
will be reset everyUpdate
. To avoid that, you could declare it asstatic int test
, but you've essentially written the first example again.So, they are very different things, but will have similar performance.