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

前端 未结 3 1706
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 10:10

I\'m timing the difference between various ways to print text to standard output. I\'m testing cout, printf, and ostringstream using both

3条回答
  •  别跟我提以往
    2021-02-15 10:44

    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.

提交回复
热议问题