Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Why we should avoid using std::endl in C++
In this article, we will see why we should avoid the std::endl while printing lines into the console or a file. We use std::endl to create a new line after the current line. For a few lines of I/O operations, it is not causing any problems. However, a large number of I/O tasks decreases performance.
Why We Avoid Using std::endl
There are the following reasons to avoid endl:
- 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 programmer's task; the operating system is responsible for it. Each time it requests flushing, it requests from the operating system. This request is comparatively expensive.
- We do not need to flush buffers every time after writing some lines, as the I/O streams automatically clear the buffer when it is full.
- If we examine the required time to write nearly 10000 lines of text into a file by using
std::endl, and using '\n', we can easily see the difference. The code that usesstd::endltakes nearly two times more times to complete the task compared to using ?\n? after it.
Example
In this C++ example, we compare the '\n' and 'endl'. The 'endl' causes the program to be slow, but '\n' does not trigger a flush. So, it is faster than 'endl':
#include <iostream>
#include <chrono>
using namespace std;
int main() {
auto start1 = chrono::high_resolution_clock::now();
for (int i = 0; i < 10000; ++i) {
// Flushes the buffer each time
cout << "Using std::endl" << endl;
}
auto end1 = chrono::high_resolution_clock::now();
auto start2 = chrono::high_resolution_clock::now();
for (int i = 0; i < 1000; ++i) {
cout << "Using \n\n";
}
auto end2 = chrono::high_resolution_clock::now();
cout << "Time taken with std::endl: " <<
chrono::duration_cast < chrono::milliseconds > (end1 - start1).count() <<
" ms\n";
cout << "Time taken with \n: " <<
chrono::duration_cast < chrono::milliseconds > (end2 - start2).count() <<
" ms\n";
return 0;
}
After executing the above code, we can see that the time difference between 'endl' and '\n'?
Time taken with std::endl: 12 ms Time taken with \n: 1 ms
Advertisements
