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
- Memory leak in C++ and How to avoid it?
- What are Wild Pointers? How can we avoid?
- Vector of Vectors in C++ STL with Examples
- Array of Vectors in C++ STL
- Difference between Virtual function and Pure virtual function in C++
- cin get() in C++ with Examples
- Difference between Increment and Decrement Operators
- Map of Vectors in C++ STL with Examples
- Problem in comparing Floating point numbers and how to compare them correctly?
- exit(0) vs exit(1) in C/C++ with Examples
- C++ program to print all Even and Odd numbers from 1 to N
- Reverse the content of a file and store it in another
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Nested Loops in C++ with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.