Next: High Integrity CPP Rule 17.11  Up: 17 Standard Template Library (STL)  Previous: High Integrity CPP Rule 17.9  Contents

High Integrity CPP Guideline 17.10   Where possible pre-allocate in containers to save unnecessary reallocations.

Justification

STL containers grow as needed when elements are inserted. However, increasing the capacity of a container can be costly as it involves allocation of memory and potentially moving previously inserted elements. While this overhead is not always an issue it is better to reserve the required storage space in advance as this reduces the number of memory allocation requests and limits having to move elements.

   
   void badPushBackManyNumbers( vector< int >& vec )
   {
      // This code may result in the vector increasing
      // its capacity several times.
      //
      for ( int i = 0; i < 100; ++i )
      {
         vec.push_back( i );
      }
   }
   
   void goodPushBackManyNumbers( vector< int >& vec )
   {
      // This code cleverly preallocates so the vector only
      // increases its capacity once.
      //
      vec.reserve( vec.size() + 100 );
   
      for ( int i = 0; i < 100; ++i )
      {
         vec.push_back( i );
      }
   }
Reference

Effective STL Items 14, 30;


HICPP VERSION 2.4  http://www.codingstandard.com   Copyright: © 2007 THE PROGRAMMING RESEARCH GROUP