[英]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? 假设我想依次访问C ++容器中的所有元素,哪种方式最有效? 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. 在这个例子中,正如您所看到的,两个方法用于访问C ++容器中的元素,因此一个自然的问题是哪一个更有效。 Thanks.
谢谢。
The best bet to figure this stuff out is to do something like 1 million loops and test it. 想出这个问题的最好方法是做一些像100万个循环一样的测试。 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. 我使用ACE,但这里是我如何获得时差的一个例子。
// 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. 我发现的另一件事,如果你可以使用c ++ 11中的auto,你通常会发现一个更快的循环,然后像你所示的那样找到历史悠久的for循环。
std::vector<std::string> lNameList;
// fill in vector
for(auto& lSection : lNameList)
{
// lSection is not a string
// DO something with it
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.