如果我们在c ++中有以下两个代码片段执行相同的任务:
If we have the following 2 snippets of code in c++ that do the same task:
int a, b=somenumber; while(b > 0) { a = b % 3; b /= 3; }或
int b=somenumber; while(b > 0) { int a=b%3; b /= 3; }我不太了解计算机体系结构/ c ++设计,第一个代码更快,因为它在开始时声明整数a,并且在while循环中使用它,而在第二个代码中,每当while循环开始时声明整数a。
I don't know much about computer architecture/c++ design, but i think that the first code is faster because it declares the integer a at the beginning and just uses it in the while-loop, and in the second code the integer a is being declared everytime the while-loop starts over. Can some one help me with this, am i correct or what and why ?
推荐答案int声明是编译器的信息,不转换为必须被编码的指令。所以没有什么区别。在循环中声明int不会使循环下降。为什么不自己编译,并让编译器输出汇编代码,让你自己看看。
The int declaration is information for the compiler and does not translate to an instruction that has to be coded. So it makes no difference. Declaring the int inside the loop will not slop the loop down. Why not try compiling both for yourself and get the compiler to output assembly code so you can see for yourself.
更多推荐
什么是速度更快?
发布评论