Why in some books says that using "\n" is better than using endl | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why in some books says that using "\n" is better than using endl

I am challenging with time. Which one is fastest for me. Somebody says me that endl deletes caches and it is slows down your code and also slows down of performancy of your code.

13th Aug 2020, 8:08 PM
Mr-Powerful
Mr-Powerful - avatar
4 Answers
+ 6
Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not. https://www.educative.io/edpresso/what-is-the-difference-between-endl-and-n-in-cpp https://www.geeksforgeeks.org/endl-vs-n-in-cpp/
13th Aug 2020, 8:15 PM
Steven M
Steven M - avatar
+ 10
Well may be you doing competitive programing that's why you notice time complexity . Time complexity is very important in competitive programing so avoid to write unnecessary lines and heavy functions. Endl and '\n' both are using for line change but both have difference if you talking about performances then '\n ' is better . << '\n' would be strictly faster than << std::endl in all cases because it is exactly what std::endl does before calling flush (which can take a very long time for a file stream or TCP stream, or a very short time for an unbuffered stream, but time nonetheless) << "\n" does slightly more work than << '\n', though it’s unlikely that a single indirection caused by the use of a string instead of a character could possibly cost more than a flush even in the unbuffered case.
14th Aug 2020, 5:54 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 4
Additionally to what Steven said, '\n' can be used to improve performance when writing out lots of lines, in one test I ran, from 3 seconds down to 0.1 seconds thereabouts.
13th Aug 2020, 9:30 PM
Ockert van Schalkwyk
Ockert van Schalkwyk - avatar
+ 1
because endl is stored in a header file so whenever u use endl u are about to use the header also.So it will increase the code a bit. but for "\n" it compiler dependent so when the compiler sees "\n" it will print new line.So the code is at the same size.
14th Aug 2020, 1:13 PM
Krishnaprasanth D V
Krishnaprasanth D V - avatar