Why we should avoid using std::endl in C++


In this section we will see why we should avoid the std::endl while printing lines into console or a file. We use std::endl for creating a newline after the current line. For few lines of IO operations, it is not making any problems. But for large amount of IO tasks, it decreases the performance.

The endl is used to create new lines, but it does not send to the new line only, after sending the cursor to the next line it flushes the buffer each time.

The flushing of buffers is not the programmers task; the operating system is responsible for it. Each time it requests for flushing, it requests to the operating system. This requesting is comparatively expensive. And we don’t really need to flush buffers every time after writing some lines. The IO streams automatically clears the buffer when it is full.

If we analyze the required time to write nearly 100000 lines of texts into file by using std::endl, and using ‘\n’ we can easily see the difference. The code which is using std::endl is taking nearly two times more times to complete the task compared to using ‘\n’ after it.

Updated on: 30-Jul-2019

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements