问题描述
我使用using 声明比使用显式std::
方式使用标准库对象更多.我有一个问题,即使用使用声明、使用声明和直接使用标准库中的名称是否会提高性能.
I use using declarations more than using the explicit std::
way for using the standard library objects. I got this question of whether is there any performance increase with using using declarations, using declaratives and using names directly from the standard library.
例如:
要打印出Hello world",我们可以这样写:
To print out "Hello world" we can write the following ways:
通过使用纯粹的
std::
方式:
std::cout <<"Hello world";
通过使用使用声明:
使用 std::cout;cout<<"Hello world";
通过使用使用声明性:
using namespace std;cout<<"Hello world";
那么,以上哪种方法的性能最好?更高效?
推荐答案
所有三种方法都将产生相同的运行时代码,从而产生相同的性能.(通过切换到汇编输出轻松验证,例如 g++ -O3 -S test.cpp
).
All three methods will result in the same runtime code, and thus performance. (easily verified by switching to assembly output, e.g. g++ -O3 -S test.cpp
).
如果您谈论的是编译时间,这不太可能产生任何可衡量的影响.理论上完全限定名称 (::std::cout
) 可以减少需要检查的潜在符号的数量.但是,磁盘 I/O 很可能要重要得多.事实上,我运行了一个测试,编译了一个简单程序 100 次,分为三个变体:::std::cout
、std::cout
和 using namespace std;cout
.即使在没有优化(使符号查找尽可能重要)和快速 SSD(以最小化磁盘 I/O 时间)的情况下进行编译时,任何差异都低于噪音水平.
Should you be talking about compile time, it is very unlikely that this would have any measurable impact. Theoretically fully qualifying the name (::std::cout
) could reduce the number of potential symbols that need to be checked. However, disk I/O will in all likelihood be far more significant. In fact, I ran a test compiling a simple program 100 times in three variants: ::std::cout
, std::cout
and using namespace std; cout
. Even when compiling without optimizations (to make symbol lookup as significant as possible) and on a fast SSD (to minimize disk I/O times) any difference was below the noise level.
这篇关于C++ 性能:使用声明性 Vs 使用声明 Vs 使用直接来自库的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!