TL DR: In general, using '\n' instead of std::endl is faster because std::endl
Explanation: std::endl causes a buffer std::endl , while '\n' does not. However, you may or may not notice any acceleration depending on the testing method that you apply.
Consider the following test files:
endl.cpp
#include <iostream> int main() { for ( int i = 0 ; i < 1000000 ; i++ ) { std::cout << i << std::endl; } }
slashn.cpp
#include <iostream> int main() { for ( int i = 0 ; i < 1000000 ; i++ ) { std::cout << i << '\n'; } }
Both of them compiled using g++ on my Linux system and pass the following tests:
1. time ./a.out
Endl.cpp requires 19.415s.
Slashn.cpp requires 19.312 s.
2. time ./a.out >/dev/null
Endl.cpp requires 0.397s
0.153s is required for slashn.cpp
3. time ./a.out >temp
Endl.cpp requires 2.255s
Slashn.cpp requires 0.165s
Conclusion: '\n' definitely faster (even practically), but the difference in speed may depend on other factors. In the case of the terminal window, the limiting factor seems to depend on how quickly the terminal itself can display text. Since the text is displayed on the screen, as well as automatic scrolling, etc., a significant slowdown occurs during execution. On the other hand, for regular files (for example, the temp example above), the speed with which the buffer is reset greatly affects it. In the case of some special files (e.g. /dev/null above), since the data is just sunk into a black hole, flushing seems to have no effect.
source share