1 .. title:: clang-tidy - performance-avoid-endl
4 ============================
6 Checks for uses of ``std::endl`` on streams and suggests using the newline
7 character ``'\n'`` instead.
10 Using ``std::endl`` on streams can be less efficient than using the newline
11 character ``'\n'`` because ``std::endl`` performs two operations: it writes a
12 newline character to the output stream and then flushes the stream buffer.
13 Writing a single newline character using ``'\n'`` does not trigger a flush,
14 which can improve performance. In addition, flushing the stream buffer can
15 cause additional overhead when working with streams that are buffered.
19 Consider the following code:
26 std::cout << "Hello" << std::endl;
29 Which gets transformed into:
36 std::cout << "Hello" << '\n';
39 This code writes a single newline character to the ``std::cout`` stream without
40 flushing the stream buffer.
42 Additionally, it is important to note that the standard C++ streams (like
43 ``std::cerr``, ``std::wcerr``, ``std::clog`` and ``std::wclog``)
44 always flush after a write operation, unless ``std::ios_base::sync_with_stdio``
45 is set to ``false``. regardless of whether ``std::endl`` or ``'\n'`` is used.
46 Therefore, using ``'\n'`` with these streams will not
47 result in any performance gain, but it is still recommended to use
48 ``'\n'`` for consistency and readability.
50 If you do need to flush the stream buffer, you can use ``std::flush``
58 std::cout << "Hello\n" << std::flush;