Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient/neat: clearing an existing stringstream or creating a new one?

Simple question just out of curiosity.

Multiple methods on a class need to use a stringstream, or specifically an ostringstream.

1) Have a stringstream variable as a class member and then just clear it before using it i.e. msg.str("")

2) Create a new stringstream variable locally in each method each time you need to use it.

Which is the best way of implementing this, in terms of efficiency and neatness?

My hunch is option 1, but not sure if the initial construction combined with each call to str() would be worse?

P.S. I've read Initializing.. which one is more efficient? and Which is quicker/more efficient?, my next step would be for me to look into profiling and writing a small test app, but I felt asking might be quicker :-)

like image 428
Adam Marshall Avatar asked Jan 06 '12 10:01

Adam Marshall


1 Answers

Don't use stringstream to begin with. Use either istringstream or ostringstream, which ever is appropriate. And only use it once; clearing it is a complex operations, requiring several lines of code, and it is easy to forget something. msg.str("") doesn't begin to address all of the state. You also need to reset the formatting flags, the error status, the exception mask, and any additional formatting information set in variables acquired by means of xalloc.

like image 138
James Kanze Avatar answered Oct 10 '22 00:10

James Kanze