Actually, IOStreams don't have to be slow! It is a matter of implementing them in a reasonable way to make them fast, though. Most standard C++ library don't seem to pay too much attention to implement IOStreams. A long time ago when my CXXRT was still maintained it was about as fast as stdio - when used correctly!
Note that there are few performance traps for users laid out with IOStreams, however. The following guidelines apply to all IOStream implementations but especially to those which are tailored to be fast:
- When using
std::cin
, std::cout
, etc. you need to call std::sync_with_stdio(false)
! Without this call, any use of the standard stream objects is required to synchronize with C's standard streams. Of course, when using std::sync_with_stdio(false)
it is assumed that you don't mix std::cin
with stdin
, std::cout
with stdout
, etc.
- Do not use
std::endl
as it mandates many unnecessary flushes of any buffer. Likewise, don't set std::ios_base::unitbuf
or use std::flush
unnecessarily.
- When creating your own stream buffers (OK, few users do), make sure they do use an internal buffer! Processing individual characters jumps through multiple conditions and a
virtual
function which makes it hideously slow.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…