In C++, a newline could be printed using std::endl or adding a “n” to the end of the printed text. Though in the latter case, the output buffer is not flushed until it is full, but this does not hinder output time.
It seems running std::endl is much slower than using “n”. For example,
for(int i = 0; i < 1000000000; i++){
cout << "Hello Worldn";
}
saves many seconds of time compared to
for(int i = 0; i < 1000000000; i++){
cout << "Hello World" << endl;
}
Since c++ automatically flushes the output buffer when it is full, why do we even bother using std::endl to flush buffers that are not full when we could replace it with “n” and let c++ automatically flush full buffers for us?
Andrew Wang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.