C++: std::endl versus \n

Recently I started a second, deeper reading of the C++ programmer bible and I noticed something which I had overlooked before. Up next is the Hello World example from the book:

int main()
{
   std::cout << "Hello, World!\n";
}

Why does Bjarne use \n instead of std::endl? Weren't we taught that the latter is more portable, since it maps to \n in *ix and \r\n in Windows?

Stroustrup doesn't say anything about this, but after some googling, it turns out that using std::endl induce a stream flush. What does this mean? As you might know, most commercial programs, operating systems and hardware do I/O buffering, which means that output operations are not directly performed on the physical media. They are done to a buffer, and when it fills up, its contents are "flushed" to the media. This reduces the time spent accessing the media, which is always more time consuming than accessing the buffer.

In the Hello World example the difference is negligible, but if we used std::endl in a tight loop, the difference might be measurable.

So, in conclusion, we should use std::endl in those cases in which portability is a higher priority than performance. This will be true most of the times. However, if time performance is a strong requirement, or if we are trying to speed up our code after profiling and detecting the bottleneck, "\n", "\r\n" or the line break characters of the OS(s) will do.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x