| 1 |
.. title:: clang-tidy - performance-avoid-endl |
| 2 |
|
| 3 |
performance-avoid-endl |
| 4 |
============================ |
| 5 |
|
| 6 |
Checks for uses of ``std::endl`` on streams and suggests using the newline |
| 7 |
character ``'\n'`` instead. |
| 8 |
|
| 9 |
Rationale: |
| 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. |
| 16 |
|
| 17 |
Example: |
| 18 |
|
| 19 |
Consider the following code: |
| 20 |
|
| 21 |
.. code-block:: c++ |
| 22 |
|
| 23 |
#include <iostream> |
| 24 |
|
| 25 |
int main() { |
| 26 |
std::cout << "Hello" << std::endl; |
| 27 |
} |
| 28 |
|
| 29 |
Which gets transformed into: |
| 30 |
|
| 31 |
.. code-block:: c++ |
| 32 |
|
| 33 |
#include <iostream> |
| 34 |
|
| 35 |
int main() { |
| 36 |
std::cout << "Hello" << '\n'; |
| 37 |
} |
| 38 |
|
| 39 |
This code writes a single newline character to the ``std::cout`` stream without |
| 40 |
flushing the stream buffer. |
| 41 |
|
| 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. |
| 49 |
|
| 50 |
If you do need to flush the stream buffer, you can use ``std::flush`` |
| 51 |
explicitly like this: |
| 52 |
|
| 53 |
.. code-block:: c++ |
| 54 |
|
| 55 |
#include <iostream> |
| 56 |
|
| 57 |
int main() { |
| 58 |
std::cout << "Hello\n" << std::flush; |
| 59 |
} |