are std::strings magic?

I was experimenting tonight with containers.
simply reading word by word a copy of don quixote into a container,
e.g: vector<string> and then dumping it all out again.

so i thought maybe if I pass the string as a pointer, then,
as it was not being copied many times it would naturally speed it up.

strangely it was slower!

on a set<string> the book took 2 seconds with string and 5 seconds
with string*

surprising?





std::string uses shared references to the actual character data. So when you do a string copy you don't actually copy all the data, you merely copy a pointer to the data.

I'm not sure why a pointer would be slower than a string (seeing as strings contain pointers) but I am also not surprised that strings are very quick to copy.
Last edited on
ah yes I was using a smart pointer as recomended.

just tried again, the times are closer again.
It seems set goes odd
when using boost::shared_ptr
i lost loads of data.

need to find out why.

still it's cool.
no need to worry about slinging strings about.
Last edited on
If you are putting pointers in the container, it means you are doing more memory allocations.

 
words.push_back( new std::string( w ) );


= 3 allocations:
1 for allocating a new node in set's internal data structure;
1 for the new std::string;
1 somewhere for std::string allocating it's internal buffer
(assuming there is only one; depends on your code)

 
words.push_back( std::string( w ) );


= 2 allocations:
1 for allocating a new node in set's internal data structure;
1 somewhere for std::string allocating it's internal buffer
(assuming there is only one; depends on your code)
@jsmith:
the first example is not putting pointer in the container...it is putting a string object...
similarly the second one is also putting the string object...

As far as i think putting pointer inside a container shall follow the syntax:

1
2
3
std::string* str = new std::string("Hello");
std::vector<std::string*> vecPstr;
vecPstr.push_back(str);
@ankitsingh12:
new std::string(w) returns a pointer to a string. You should know that; you used new in your example.

That said, I hope words in that first example takes std::string*s.

-Albatross
Last edited on
conclusion:

don't worry about run time speed when slinging strings about.
just use 'em.
eehhhhh

I'm not sure that's good advice.
1 for allocating a new node in set's internal data structure;
1 for the new std::string;
1 somewhere for std::string allocating it's internal buffer
Isn't the second step dwarfed in length by the other two steps? Particularly if the string is long and/or the set is big.
Topic archived. No new replies allowed.