Performance of pIter != cont.end() in for loop

后端 未结 7 435
面向向阳花
面向向阳花 2021-01-07 18:11

I was getting through \"Exceptional C++\" by Herb Sutter lately, and I have serious doubts about a particular recommendation he gives in Item 6 - Temporary Objects.

相关标签:
7条回答
  • 2021-01-07 18:36

    I've compiled the following slightly hacky code using g++ 4.7.2 with -O3 -std=c++11, and got identical assembly for both functions:

    #include <list>
    #include <string>
    
    using namespace std;
    
    struct Employee: public string { string addr; };
    
    string FindAddr1(list<Employee> emps, string name)
    {
      for (list<Employee>::const_iterator i = emps.begin(); i != emps.end(); i++)
      {
        if( *i == name )
        {
          return i->addr;
        }
      }
      return "";
    }
    
    string FindAddr2(list<Employee> emps, string name)
    {
      list<Employee>::const_iterator end(emps.end());
      for (list<Employee>::const_iterator i = emps.begin(); i != end; i++)
      {
        if( *i == name )
        {
          return i->addr;
        }
      }
      return "";
    }
    

    In any event, I think the choice between the two versions should be primarily based on grounds of readability. Without profiling data, micro-optimizations like this to me look premature.

    0 讨论(0)
提交回复
热议问题