Possible Duplicate:
C++: “std::endl” vs “\n”
In Accelerated C++, two things are mentioned:
-
Most systems take a significant amount of time to write characters to an output device. Because of this, C++ accumulates characters to be written in a buffer and waits for the buffer to be flushed.
-
One way a buffer can be flushed is if we explicitly tell it to do so by using
std::endl.
This made me wonder: Obviously the benefits would be very small and unnoticeable for everything except the largest of outputs, but is using "\n" faster than using std::endl, or does "\n" also flush a buffer?
Using ‘\n’ does not flush the buffer and is indeed faster than using std::endl.
In typical I/O, output is buffered before it’s written to the intended device. This way, when writing to slow to access devices(like files), it doesn’t have to access the device after every single character. Flushing “flushes” the buffer onto the device, causing a definite performance overhead.
-Adapted from: C++ – endl and flushing the buffer