istringstream and optimization

M

mathieu

Hello there,

Could anyone comment on the following code(*). I would like to
optimize the following line:

is.str( std::string(s,4) );

Seems to me that allocation+initialization of the std::string is a
bit complex for such simple task. Looks to me that I should be able to
manipulate the rdbuf internals.

Comments welcome, thanks.
Mathieu

(*)
#include <iostream>
#include <sstream>

int main()
{
// 9728
const char s[] = "\0&\0\0";
uint32_t n = 0;
memcpy(&n, s, 4);
std::cout << n << std::endl;

uint32_t nn = 0;
std::istringstream is;
is.str( std::string(s,4) ); // <----- this line
is.read( reinterpret_cast<char*>(&nn), 4);
std::cout << is.str() << "->" << nn << std::endl;

std::eek:stringstream os;
os.write( reinterpret_cast<char*>(&n), 4);
std::cout << n << "->" << os.str() << std::endl;

return 0;
}
 
R

red floyd

mathieu said:
Hello there,

Could anyone comment on the following code(*). I would like to
optimize the following line:

is.str( std::string(s,4) );

Seems to me that allocation+initialization of the std::string is a
bit complex for such simple task. Looks to me that I should be able to
manipulate the rdbuf internals.
Have you benchmarked to see if this actually is a problem? What is the
obsession that people seem to have with premature optimization, without
regard to Hoare's/Knuth's Law ("Premature optimization is the root of
all evil")?

Manipulating the rdbuf internals will most likely lead to less
understandable and therefore less maintainable code.

I'd code for what my last job used to call the "X-abilities"
(reliability, scalability, maintainability), and worry about
micromanaging performance later, after testing and benchmarks indicate a
problem.

But that's just my opinion.
 
M

mathieu

And the solution is...that you are indeed right !
I was going back and forth in my istringstream/ostringstream. Redoing
my templates I was able to skip this step :p

Mathieu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Chatbot 0
static istringstream 9
istringstream question 7
TF-IDF 2
Crossword 2
Crossword 14
Avoiding copy: char* -> istringstream 7
Decompressed bitmap image doesn't properly render when using WinGDI 2

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top