0

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.

For instance:

To print out "Hello world" we can write the following ways:

  • By using the bare std:: way:

    std::cout << "Hello world";

  • By using using declaration:

    using std::cout; cout << "Hello world";

  • By using using declarative:

    using namespace std; cout << "Hello world";

So, Which of the above methods has the best perfomance? and more efficient?

Deepam Sarmah
  • 155
  • 1
  • 8

3 Answers3

8

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).

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.

Joe
  • 6,497
  • 4
  • 29
  • 55
2

This has no effect on run-time performance. using is applied at compile time

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

These methods are fully the same to compare in run-time, because using is previously compiled.

But if you want to create your own namespace you should be careful.

#include <iostream>

namespace test
{
   int a = 1;
}

using namespace test;

int main()
{
   int a = 3;
   std::cout << test::a << std::endl; // prints 1
   std::cout << a << std::endl; // be careful, prints 3
   return 0;
}

When you are using the method above you make your namespace global. It means that when you declare another variable a in the main() function, it will hide the variable a from test. You can still have the access to this variable by typing test::a, but a without test:: will refer to the local variable.

To avoid it, don't use using namespace your_namespace if you don't need it. It's better to write one more word to make your code safe.

If you are using some variables from namespace very often you could declare it in this way using your_namespace::variable.

Stivius
  • 72
  • 7