xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/performance/avoid-endl.rst (revision 1d90376a48406336ed73d3fc3f8f6aa90f90cb0f)
1.. title:: clang-tidy - performance-avoid-endl
2
3performance-avoid-endl
4============================
5
6Checks for uses of ``std::endl`` on streams and suggests using the newline
7character ``'\n'`` instead.
8
9Rationale:
10Using ``std::endl`` on streams can be less efficient than using the newline
11character ``'\n'`` because ``std::endl`` performs two operations: it writes a
12newline character to the output stream and then flushes the stream buffer.
13Writing a single newline character using ``'\n'`` does not trigger a flush,
14which can improve performance. In addition, flushing the stream buffer can
15cause additional overhead when working with streams that are buffered.
16
17Example:
18
19Consider the following code:
20
21.. code-block:: c++
22
23    #include <iostream>
24
25    int main() {
26      std::cout << "Hello" << std::endl;
27    }
28
29Which gets transformed into:
30
31.. code-block:: c++
32
33    #include <iostream>
34
35    int main() {
36      std::cout << "Hello" << '\n';
37    }
38
39This code writes a single newline character to the ``std::cout`` stream without
40flushing the stream buffer.
41
42Additionally, it is important to note that the standard C++ streams (like
43``std::cerr``, ``std::wcerr``, ``std::clog`` and ``std::wclog``)
44always flush after a write operation, unless ``std::ios_base::sync_with_stdio``
45is set to ``false``. regardless of whether ``std::endl`` or ``'\n'`` is used.
46Therefore, using ``'\n'`` with these streams will not
47result in any performance gain, but it is still recommended to use
48``'\n'`` for consistency and readability.
49
50If you do need to flush the stream buffer, you can use ``std::flush``
51explicitly like this:
52
53.. code-block:: c++
54
55    #include <iostream>
56
57    int main() {
58      std::cout << "Hello\n" << std::flush;
59    }
60