Why we should avoid using std::endl
It is a common practice to use std::endl to print newlines while using cout. For small programs with very little I/O operations this practice is acceptable, but if the bulk of I/O operations increase, then the efficiency of the program is compromised.
std::endl not only adds newlines to the stream, it also flushes the buffer each time it is used.Thus when we write
cout << std::endl
We are actually doing something like this
cout << '\n' << std::flush;
Flushing of buffers is an Operating System task. Each time the buffer is flushed, a request has to be made to the OS and these requests are comparatively expensive. Furthermore, we don’t really need to flush the buffer every time we write something to the stream, since the buffers get flushed automatically when they get full. In the rare cases we do need to perform flushing, we can explicitly specify the operation using either cout.flush() or by inserting std::flush into the stream.
Writing ‘\n’ characters directly to the stream is more efficient since it doesn’t force a flush like std::endl.
Demonstration of performance impact
The following C++ program demonstrates the performance impact of std::endl. We write 100000 strings to two files once using std::endl and then again using ‘\n’. In each case, we measure the execution time taken and print these times
Output: (Machine Dependent)
Writing to file using endl took 3272 microseconds Writing to file using \n took 1533 microseconds
As seen from the output std::endl took nearly double the time. On some systems, the performance impact could be even worse. Note that it is guaranteed that std::endl will take more time than printing ‘\n’ directly to the stream.
C++ Weekly – Episode 7