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

后端 未结 7 437
面向向阳花
面向向阳花 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 
    #include 
    
    using namespace std;
    
    struct Employee: public string { string addr; };
    
    string FindAddr1(list emps, string name)
    {
      for (list::const_iterator i = emps.begin(); i != emps.end(); i++)
      {
        if( *i == name )
        {
          return i->addr;
        }
      }
      return "";
    }
    
    string FindAddr2(list emps, string name)
    {
      list::const_iterator end(emps.end());
      for (list::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.

提交回复
热议问题