将变量声明放在后面是否更节省内存或者更高效?
示例:
int x;
code
..
.
.
. x is able to be used in all this code
.
actually used here
.
end
对比
code
..
.
.
.
int x;
actually used here
.
end
谢谢。
将变量声明放在后面是否更节省内存或者更高效?
示例:
int x;
code
..
.
.
. x is able to be used in all this code
.
actually used here
.
end
对比
code
..
.
.
.
int x;
actually used here
.
end
请按照逻辑编写代码(通常更接近实际使用)。编译器可以并且会发现这样的问题,并生成最适合目标架构的代码。
你的时间比试图猜测编译器和处理器缓存之间的交互要宝贵得多。
例如,在x86上,此程序为:
#include <iostream>
int main() {
for (int j = 0; j < 1000; ++j) {
std::cout << j << std::endl;
}
int i = 999;
std::cout << i << std::endl;
}
相比之下:
#include <iostream>
int main() {
int i = 999;
for (int j = 0; j < 1000; ++j) {
std::cout << j << std::endl;
}
std::cout << i << std::endl;
}
编译使用的:
g++ -Wall -Wextra -O4 -S measure.c
g++ -Wall -Wextra -O4 -S measure2.c
diff measure*.s
命令会显示:< .file "measure2.cc"
---
> .file "measure.cc"
即使对于:
#include <iostream>
namespace {
struct foo {
foo() { }
~foo() { }
};
}
std::ostream& operator<<(std::ostream& out, const foo&) {
return out << "foo";
}
int main() {
for (int j = 0; j < 1000; ++j) {
std::cout << j << std::endl;
}
foo i;
std::cout << i << std::endl;
}
vs
#include <iostream>
namespace {
struct foo {
foo() { }
~foo() { }
};
}
std::ostream& operator<<(std::ostream& out, const foo&) {
return out << "foo";
}
int main() {
foo i;
for (int j = 0; j < 1000; ++j) {
std::cout << j << std::endl;
}
std::cout << i << std::endl;
}
g++ -S
生成的汇编代码差异仅在文件名上有所区别,因为没有副作用。如果有副作用,则会决定您构建对象的位置-您希望何时发生副作用?
int
,从性能角度来看并不重要。对于class
类型,变量定义包括构造函数的调用,如果控制流跳过该变量,则可以省略构造函数调用。此外,对于基本类型和class
类型,应将定义延迟至少到有足够信息使这样的变量有意义的点。对于非默认可构造类类型,这是强制性的;对于其他类型,它可能不是,但它会强制你使用未初始化状态(如-1或其他无效值)。您应该尽可能在最小的范围内尽可能晚地定义变量;有时从性能角度来看可能并不重要,但从设计上来说总是很重要的。对于简单类型来说,无论是哪种方式都没有更高的内存或计算效率。但对于更复杂的类型,将内容保持在缓存中(从构建时开始)并靠近使用它们的位置可能更加有效。这也可以最小化内存保留的时间。
x
保留在使用它的地方,这样程序员就能保持头脑清晰、专注于算法而不是这些细节。请注意,这并不改变原意。 - Johannes Schaub - litb