View Single Post
Old 06-29-2005, 06:50 PM   #9 (permalink)
Rashakil Fol
Registered User
 
Join Date: Jun 2005
Posts: 3
Rashakil Fol is on a distinguished road
Quote:
Originally Posted by redhead
Then compare it to the version, where you parse by reference.. You'll soon notice they are the same.
Huh? Are you talking about this?
Code:
  void swap(std::string& string1, std::string& string2)
  {
    std::string holder;
    holder = string1;
    string1 = string2;
    string2 = holder;
  }
This is not the same as the string class's swap method. The string class's swap method simply swaps the objects' pointers that point to their dynamically allocated arrays, which means that no matter how large the strings are, the operation takes the same amount of time.

The code above copies characters around -- if string1 and string2 are fifty characters long, then fifty characters will get copied from string1 to holder, then fifty characters will get copied from string2 to string1, and then fifty characters will get copied from holder to string2. Also, holder will have to perform a memory allocation when it gets assigned from string1.

This is far more expensive than the swap method, which only has three pairs of pointers to swap, everytime, with no extra allocations in between.
Rashakil Fol is offline   Reply With Quote