Why is std::endl often considered slower than using \n?
Last updated
std::endl does two things: it inserts a newline AND flushes the stream's buffer, whereas '\n' only inserts the newline. The forced flush is the expensive part, since each flush can trigger a system call and defeats buffering.
What each does:
std::endlis equivalent to writing'\n'then callingflush().'\n'just appends a newline and lets the buffer flush naturally.
Why the flush hurts:
In a loop printing many lines,
std::endlforces a flush every iteration, turning buffered output into many small writes.Buffering exists precisely to batch I/O, so repeated flushing throws that benefit away.
When endl is fine:
When you actually need the output visible immediately (e.g. before a crash, or interactive prompts).
Default to
'\n'and flush explicitly only when required.