feelfree
feelfree

Reputation: 11753

What is the most efficient way of accessing elements in a C++ container?

Suppose I want to sequentially access all the elements in a C++ container, which way is the most efficient one? I illustrated my question in the following example:

std::vector<int> abc;
abc.push_back(3);
abc.push_back(4);
...
...

for(int i=0; i<abc.size(); i++)
{
  abc[i];
}

std::vector<int>::iterator it = abc.begin();
std::vector<int>::iterator itEnd = abc.end();
while(it != itEnd)
{
     (*it);
     it++;
}

In this example, as you can see, two methods are used to access elements in the C++ container, so a natural question is which one is more efficient. Thanks.

Upvotes: 3

Views: 1010

Answers (1)

Brian S
Brian S

Reputation: 3234

The best bet to figure this stuff out is to do something like 1 million loops and test it. Compilers vary. Make sure to test it in release mode.

I use ACE, but here is an example of how I get the time difference.

  // Log how long each module takes.
      ACE_Time_Value    lSendStart;
      ACE_Time_Value    lDifference;

       // Start keeping track of how long this takes
      lSendStart = ACE_OS::gettimeofday();

      // Figure out how long we took.
      lDifference = ACE_OS::gettimeofday() - lSendStart;
       // Log how long we took
      PLALOG_INFO( mLogger, ACE_TEXT( "doProcessing took ") <<lDifference.sec () << ACE_TEXT( "seconds(s) and ") << (lDifference.usec ()) <<
                    ACE_TEXT(" micro second(s) to process." ), "" );

So Get the start time, loop it a million times, get the difference, then do the same loop the other way.

Another thing I have found, if you can use the auto from c++11, you will generally find a faster loop then the historic for loop like you have shown.

   std::vector<std::string> lNameList; 
   // fill in vector
   for(auto& lSection : lNameList)
   {
      // lSection is not a string
      // DO something with it

   }

Upvotes: 6

Related Questions