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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Memory leak in C++ and How to avoid it?
- What are Wild Pointers? How can we avoid?
- lvalues references and rvalues references in C++ with Examples
- Difference between cout and std::cout in C++
- C++ program to check whether a String is a Pangram or not
- Difference between pair in Multiset and Multimap in C++ STL
- How to use unordered_map efficiently in C++
- Header files in C/C++ with Examples
- Trigraphs in C++ with Examples
- Difference Between DART and C++
- How to fix auto keyword error in Dev-C++
- Important functions of STL Components in C++
- Array of Structures vs. Array within a Structure in C/C++
- How to store a very large number of more than 100 digits in C++
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.