File: avoid-endl.rst

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (59 lines) | stat: -rw-r--r-- 1,731 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
.. title:: clang-tidy - performance-avoid-endl

performance-avoid-endl
============================

Checks for uses of ``std::endl`` on streams and suggests using the newline
character ``'\n'`` instead.

Rationale:
Using ``std::endl`` on streams can be less efficient than using the newline
character ``'\n'`` because ``std::endl`` performs two operations: it writes a
newline character to the output stream and then flushes the stream buffer.
Writing a single newline character using ``'\n'`` does not trigger a flush,
which can improve performance. In addition, flushing the stream buffer can
cause additional overhead when working with streams that are buffered.

Example:

Consider the following code:

.. code-block:: c++

    #include <iostream>

    int main() {
      std::cout << "Hello" << std::endl;
    }

Which gets transformed into:

.. code-block:: c++

    #include <iostream>

    int main() {
      std::cout << "Hello" << '\n';
    }

This code writes a single newline character to the ``std::cout`` stream without
flushing the stream buffer.

Additionally, it is important to note that the standard C++ streams (like
``std::cerr``, ``std::wcerr``, ``std::clog`` and ``std::wclog``)
always flush after a write operation, unless ``std::ios_base::sync_with_stdio``
is set to ``false``. regardless of whether ``std::endl`` or ``'\n'`` is used.
Therefore, using ``'\n'`` with these streams will not
result in any performance gain, but it is still recommended to use
``'\n'`` for consistency and readability.

If you do need to flush the stream buffer, you can use ``std::flush``
explicitly like this:

.. code-block:: c++

    #include <iostream>

    int main() {
      std::cout << "Hello\n" << std::flush;
    }