Skip navigation

I want to believe iteration style doesn’t make a difference as much as the next guy, but the fact is, it does.

In order, performance goes

For std::vector:
integer indexing FASTER THAN range based for FASTER THAN traditional iterators

For std::list:
range based for FASTER THAN traditional iterators

You can quote me on that. A test below proves it with a simple example.




#include <stdio.h>
#include <vector>
#include <list>
using namespace std ;

/////#include "Timer.h" // TIMER.h pasted below
#include <sys/time.h>

struct Timer
{
  timeval start ;
  
  Timer() { reset(); }
  
  void reset() {
    gettimeofday( &start, NULL ) ;
  }
  
  double getTime() const {
    timeval end ;
    gettimeofday( &end, NULL ) ;
    
    return end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1e6 ;
  }
  
} ;


struct O{
  int a ;
  float b;
  
  O( int ia, float ib ):a(ia),b(ib){}
  
  void print()
  {
    printf( "%d %f\n", a,b ) ;
  }
  
  void doIt()
  {
    a++;
    b++;
  }
} ;

int TESTS = 10000000 ;

int main(int argc, const char * argv[])
{
  vector os ;
  
  os.push_back( O(2, 2.2 ) ) ;
  os.push_back( O(3, 3.3 ) ) ;
  os.push_back( O(4, 4.4 ) ) ;
  
  Timer t ;
  
  t.reset() ;
  for( int i = 0 ; i < TESTS ; i++ )
  {
    for( vector::iterator iter = os.begin() ; iter != os.end(); ++iter )
    {
      iter->doIt();
    }
  }
  printf( "TRADITIONAL ITERATOR : %f\n", t.getTime() ) ; // 0.755 sec
  
  t.reset() ;
  for( int i = 0 ; i < TESTS ; i++ )
  {
    for( O& entry : os ) // note: if you pass by value, it's even faster
    {
      entry.doIt();
    }
  }
  printf( "NEWFANGLED RANGE BASED for : style Time %f\n", t.getTime() ) ; // 0.493 sec
  
  
  t.reset();
  for( int i = 0 ; i < TESTS ; i++ )
  {
    for( int j = 0 ; j < os.size() ; j++ )
    {
      os[j].doIt();
    }
  }
  printf( "INTEGER INDEXING Time %f\n", t.getTime() ) ; // 0.243 sec
  
  
  
  
  
  
  return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: