Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Move Semantics: Make Your Next Move -3 : Page 3


advertisement
Container Swapping
If the swapping of two strings can be optimized dramatically by using move semantics, imagine the effect of swapping two containers in this manner. Recall that containers also use swap() implicitly, when they reallocate storage for new elements, for instance.

A copy-based container reallocation consists of these steps:

  1. Allocate a raw memory buffer that is large enough to accommodate the container's existing elements and the new ones.
  2. Copy-construct each element onto the new raw buffer.
  3. Destroy the original elements.
  4. Release the original memory buffer.

Unquestionably, this reallocation scheme is very expensive and slow.



The performance overhead of reallocation can be reduced drastically if the container moves its elements instead of copy-constructing them. Think of a vector of strings, for example. Instead of reallocating every string object using a copy-based swap, the vector can call move-based swap() to move strings from the original memory buffer to the new memory buffer. In other words, the newly constructed strings will simply swap their null buffer addresses and zero sizes with the original strings. Neither memory reallocation of string buffers nor character copying are required in this case.

Things get even better when you swap two containers. Theoretically, this operation would require member-wise copying of elements to a temporary container and a subsequent copying of each container's elements. You guessed it: a move operation can swap the contents of two containers by simply exchanging their data pointers and sizes. The performance improvement in this case is fantastic.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap