tags:

views:

83

answers:

4

Hi,

I have a situation where I read data from a struct and keep appending it to a string so that it can be sent over a socket. When the data is fairly large, this operation is taking a lot of time. Can someone suggest any alternatives?

I have a structure

struct fileInfo { int file_id; char filename[16]; double tag; }

I do a std::stringstream >>file_id and stringstream.str() this is repeated for each value, appended to a string and sent

A: 

Perhaps you should send the strings individually. If you have a streaming socket, this should make no difference to the way the data is received at the other end.

Alexander Rafferty
you mean, instead of appending, just do a send?
Rajesh
@Rajesh: He's saying, if the I/O is locally buffered, then don't worry about buffering it yourself. I'm guessing that the socket isn't buffered since most aren't.
Potatoswatter
A: 

One option is to use an std::stringstream. More specific help can only be provided if you provide more specific information. What kind of data are you streaming? How large are the chunks of data?

Space_C0wb0y
Thats what I use. I read the struct value into a stringstream and then do a .str() to get the string. Can I directly send a stringstream?
Rajesh
@Rajesh: You said you use a `string`, not a `stringstream`. They have different runtime characteristics for appending, so it's a rather important difference. What makes you say the `stringstream` is slow? What does the profiler point at specifically?
Potatoswatter
I do use a string...i append the stringstream.str to a string and then send
Rajesh
+6  A: 

std::ostringstream from <sstream> is designed for exactly that mode of operation.

ostringstream my_text;
my_text << "hello " << 2 << foo << endl; // efficiently catenate

socket.send( my_text.str() ); // get a std::string to handle data
Potatoswatter
ok. I'll give this a try. thanks
Rajesh
A: 

If you can have a rough estimate about how large the string will end up, you could use std::string::reserve() first to avoid superfluous reallocations later.

usta