$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: [Boost-users] [iostreams]Can I write data directly to the device of a stream?
From: Comet (cometliao_at_[hidden])
Date: 2010-05-20 03:31:26
Hi,
I assumed that stream wrote data directly to it's associated device,
but after a few tests I found I was wrong.
I wrote this code snippet:
<--- Code --->
int main() {
  using namespace std;
  using namespace boost::iostreams;
  string src;
  src.assign(10 * 1024, 'a');
  size_t size = src.size();
  // ContainerDevice is from boost::iostreams::example
  typedef ContainerDevice<std::vector<char> > MyDevice;
  vector<char> container;
  string str;
  container.reserve(size);
  str.reserve(size);
  for (size_t i = 0; i < 1000000; ++i) {
    // Version 1
    MyDevice device(container);
    stream<MyDevice>  io(device);
    io.write(src.c_str(), src.size());
    io.flush();
    container.clear();
    // Version 2
#if 0
    str.insert(str.end(), src.begin(), src.end());
    container.insert(container.end(), str.begin(), str.end());
    str.clear();
    container.clear();
#endif
  }
  return 0;
}
<--- Code-End --->
The first version(write data to the device by stream) is slower than the
second(copy data, then copy again to device), so I guess stream do some
unnecessary copy operations (eg: copy data to inner buffer, then copy
again from buffer to device). 
I tried replacing 
stream<MyDevice> io(device);
with
stream<MyDevice> io(device, 0, 0);
to set inner buffer size to 0, but the result was much more slower. I
set a breakpoint at 
ContainerDevice::write(const char_type* data, std::streamsize n) 
then found n passed was always 1, which means every call wrote only 1
byte.
If there is a way to write data directly to the device, my program will
be very efficient.
thanks.