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*
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.
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);