Does moving variable declaration outside of a loop actually increase performance?

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

I'm writing very processor-intensive cryptography code (C#), so I'm looking for any performance gains, no matter how small. I've heard opinions both ways on this subject.

Is there any performance benefit at all to

int smallPrime, spGen;  for (int i = 0; i 

over this?

for (int i = 0; i 

Does the compiler do this already?

回答1:

There is no performance benefit at all.

All local variables are allocated when the stack frame for the method is created, so it doesn't matter where in the method you declare them. It's only the scope of the variables that differ between the codes, and that is only information that the compiler uses at compile time.

Edit:

To verify that there is no difference, I compiled the two cases and examined the generated machine code, and it is identical for the two cases:

Declaring variables outside the loop:

            for (int i = 0; i 

Declaring variables inside the loop:

            for (int i = 0; i 


回答2:

Not really, the compiler will do that optimization for you.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!