c – 迟到声明变量更有效吗?
发布时间:2020-12-16 10:54:51 所属栏目:百科 来源:网络整理
导读:是否需要更多内存或计算效率更快地声明变量? 例: 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生成的组件差异的结果仍然相同,因为没有副作用.如果有副作用那么这将决定你构建对象的位置 – 你想在什么时候发生副作用? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读
