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?
- History of C++
- What are Forward declarations in C++
- __builtin_inf() functions of GCC compiler
- Structures in C++
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
- Machine Learning in C++
- How can we use Comma operator in place of curly braces?
- Optimally accommodate 0s and 1s from a Binary String into K buckets
- Find a number containing N - 1 set bits at even positions from the right
- Sort an array according to absolute difference with given value using Functors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.