Why does using std::endl with ostringstream affect output speed?

。_饼干妹妹 提交于 2019-12-03 13:04:59

std::endl triggers a flush of the stream, which slows down printing a lot. See http://en.cppreference.com/w/cpp/io/manip/endl

It is often recommended to not use std::endl unless you really want the stream to be flushed. If this is really important to you, depends on your use case.

Regarding why flush has a performance impact even on a ostringstream (where no flushing should happen): It seems that an implementation is required to at least construct the sentry objects. Those need to check good and tie of the ostream. The call to pubsync should be able to be optimized out. This is based on my reading of libcpp and libstdc++.

After some more reading the interesting question seems to be this: Is an implementation of basic_ostringstream::flush really required to construct the sentry object? If not, this seems like a "quality of implementation" issues to me. But I actually think it needs to because even a basic_stringbug can change to have its badbit set.

Each output operation on a stream dors multiple steps:

  • It checks if the stream is in good shape.
  • It checks if some other stream needs to flushed.
  • The sequence of characters is produced.
  • It checks if there is enough space for the written characters.
  • The use of endl calls an extra virtual function on the stream buffer.

I would personally expect that the extra virtual function call actually has relativly small impact compared to the other operations. You can verify this guess by also profiling this output:

out << "stream" << '\n';

... or even

out << "stream" << out.widen('\n');

That said, there are a number of improvements which a stream implementation can apply to cut down on checks. Whether this is done will depend on the implementation, of course.

Using std::endl is equivalent to writing

stream << "\n";
stream.flush();

Don't use std::endl unless you actually want to trigger flushing, and / or don't care about output performance.

Also, don't worry about different line endings on different platforms, your implementation will translate "\n" to the line ending appropriate for your platform.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!