2.9.08

using namespace std; a cautionary tale

OR: How a 10 minute compile bloated into a 55 minute one

When you first learn about the standard template library, you rejoice at the thought of having clever containers and algorithms at your beck and call. They are fairly straight forward and easy to use. There is just one niggling problem:

In your programmer laziness, you dont really want to type "std::" in front of every variable name/type.

Very soon, you realize that this is just a namespace and that you can get around the extra typing by entering "using namespace std;" at the beginning of your module.

If you are lazier yet, you realize that you can put "using namespace std;" into a header file, and thus avoid having to type it in each module that needs it. The world is a fun and happy place. Your "hello world" applications grow and prosper.

If your app is not trivial or small, however, this little trick will come back to haunt you. Well...actually...this little trick will come back to haunt the consultant trying to compile your huge templated library. My cover is blown, that beleaguered consultant is me.

This particular library was well known and hated for taking nearly an hour (I clocked it at 55 minutes) to compile. (This is a single DLL, mind you.) Everyone always said that there was something weird going on. Some of the savvy developers blamed the sheer number of templates that it instantiated.

They were close to the issue, but not quite right. It isn't that the compiler was chugging through so many templates that slowed the process. It was that several core header files defined had a "using namespace std;" to alleviate typing problems. This simple oversight was causing 40 minutes of lost time EVERY TIME IT BUILT. One of the developers I work with mused: "I wonder how many man hours we lost over the last 5 years?"

The problem is, of course, that by "using" the "std" namespace, you load the names of every type and function and template into the compilers memory. The more STL headers you have loaded before hand, the worse it gets. The compiler now has to search through MANY names to determine the context of something that should take barely any look up. It's like looking up your friend's number in a Braille phonebook when they live right across the street.

I just happened to notice the unwise statements. After a painful period of removing the offenders and adjusting the remaining code to compile (typedefs and std::'s all over the place). I finally saw the fruits of my labor. The library now compiles in under 10 minutes.

The morals of the story are clear:

  1. Avoid "using namespace std" in your .cpp modules. Typedefs and "using std::whatever" are better options. Make a good habit.
  2. Do not put "using namespace std" in a header file unless you project is trivially small.
  3. Never, ever, put "using namespace std" in several core header files for a large, templated library.

0 comments:

Post a Comment