Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same string to multiple streams [duplicate]

I have to send the same string (e.g. a log message) to multiple streams.
Which of the following solutions is the most efficient?

  1. Rebuild the same string for each stream and send it to the stream itself.

    outstr1 << "abc" << 123 << 1.23 << "def" << endl;  
    outstr2 << "abc" << 123 << 1.23 << "def" << endl;  
    outstr3 << "abc" << 123 << 1.23 << "def" << endl;  
    
  2. Build the string once with string's operators, and send it to all the streams.

    std::string str = "abc" + std::to_string(123) + std::to_string(1.23) + "def";  
    outstr1 << str;  
    outstr2 << str;  
    outstr3 << str;  
    
  3. Build the string once with a stream, and send it to all the streams:

    std::stringstream sstm;  
    sstm << "abc" << 123 << 1.23 << "def" << endl;  
    std::string str = sstm.str();  
    outstr1 << str;  
    outstr2 << str;  
    outstr3 << str;  
    

Some or all of these output streams could be on a RAM disk.

Any other ways to do the same thing?

like image 302
Pietro Avatar asked Feb 13 '26 23:02

Pietro


2 Answers

I would use a tee output stream. Do something like (pseudocode):

allstreams = tee(outstr1, outstr2, outstr3);
allstreams << "abc" << 123 << 1.23 << "def" << endl;

There doesn't seem to be anything in the standard c++ library to do this, but Boost has one.

See also the answers to How can I compose output streams, so output goes multiple places at once?

like image 119
Keith Randall Avatar answered Feb 15 '26 13:02

Keith Randall


Although it is unlikely that you would see much difference either way1, option #3 sounds the most plausible: unlike the first option, it does not convert ints to strings multiple times; unlike the second option, it does not allocate and delete multiple string objects for its intermediate results2. It also looks cleanest from the readability point of view: no code is duplicated, and output looks like an output, not like a concatenation.


1 Insert a mandatory disclaimer about optimization before profiling being evil here.

2 Small String Optimization may help on systems where it is supported (thanks, Prætorian), but the constructor and destructor calls for the intermediate objects are not going away.

like image 38
Sergey Kalinichenko Avatar answered Feb 15 '26 12:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!