Main Content

std::endl may cause an unnecessary flush

std::endl is used instead of the more efficient \n

Since R2020a

Description

This defect flags uses of std::endl in I/O operations and allows you to use the more efficient alternative, \n.

Risk

std::endl inserts a newline (\n) followed by a flush operation. For instance:

std::cout << "Some content" << std::endl;
is equivalent to:
std::cout << "Some content" << '\n' << std::flush;
The implicit flush operation might not be necessary or intended. If your program has many I/O operations that use std::endl, the implicit flush operation can significantly reduce program performance. Since the flush operation is implicit, in case of a performance issue, it will be difficult to track the root cause of the issue.

Fix

Use \n to enter a newline wherever possible.

If you require a flush operation, instead of std::endl, use \n followed by an explicit flush operation, for instance:

std::cout << "Some content" << '\n' << std::flush;
In this case, the analysis considers your use of a flush operation as deliberate and does not flag the use.

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

#include <fstream> 
using namespace std; 

int main() 
{ 
  ofstream aFile("file.txt"); 
  for ( int i = 0; i < 100000; i++) { 
    aFile << "Hello World " << std::endl ; 
  } 
  aFile.close();
  return 0; 
} 

In this example, an std::endl is used in a loop during a write operation on a file. Since the loop has 100000 iterations, the slight delay from each implicit flush operation can add up to a significant reduction of performance.

Use \n and Avoid Flush

In a loop with several iterations, avoid the performance reduction in I/O operations by using \n instead of std::endl.

#include <fstream> 
using namespace std; 

int main() 
{ 
  ofstream aFile("file.txt"); 
  for ( int i = 0; i < 100000; i++) { 
    aFile << "Hello World \n" ; 
  } 
  aFile.close(); 
  return 0; 
} 

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: STD_ENDL_USE
Impact: Low

Version History

Introduced in R2020a