C++ Namespace – Does It Simplify Compiler Parsing?

cnamespace

Retaining the names inside namespace will make compiler work less stressful!?

For example:

// test.cpp
#include</*iostream,vector,string,map*/>
class vec { /* ... */ };

Take 2 scenarios of main():

// scenario-1
using namespace std;  // comment this line for scenario-2
int main ()
{
  vec obj;
}

For scenario-1 where using namespace std;, several type names from namespace std will come into global scope. Thus compiler will have to check against vec if any of the type is colliding with it. If it does then generate error.

In scenario-2 where there is no using namespace, compiler just have to check vec with std, because that's the only symbol in global scope.

I am interested to know that, shouldn't it make the compiler little faster ?

Best Answer

It depends on how the compiler is designed.

It can make all symbols represented with their own full-qualified names into a binary-search tree, with a another set of "visibility scope" and a coverage table telling what is visible from where (hence the entire name structures is flattened) or it can somehow cope with your name structures or cope with your code block and scopes.

You can easily understand that the compiler performances differ a lot if the compiler developer did an orthogonal choice respect to the compiler user.

However the purpose of the code (apart the obvious doing what is required to do) is to be readable and maintainable, not to be easily compilable. If you plan to optimize compiling, you are focusing on the wrong side of software development, risking to find yourself in 5 years with a code that compiles fast, but you cannot touch anymore since you are anymore able to understand it.

Related Topic