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

后端 未结 7 442
面向向阳花
面向向阳花 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:34

    Contrary to popular belief, I don't see any difference between VC++ and gcc in this respect. I did a quick check with both g++ 4.7.2 and MS C++ 17 (aka VC++ 2012).

    In both cases I compared the code generated with the code as in the question (with headers and such added to let it compile), to the following code:

    string FindAddr(list emps, string name) 
    {
        auto end = emps.end();
        for (list::iterator i = emps.begin(); i != end; i++)
        {
            if( *i == name )
            {
                return i->addr;
            }
        }
        return "";
    }
    

    In both cases the result was essentially identical for the two pieces of code. VC++ includes line-number comments in the code, which changed because of the extra line, but that was the only difference. With g++ the output files were identical.

    Doing the same with std::vector instead of std::list, gave pretty much the same result -- no significant difference. For some reason, g++ did switch the order of operands for one instruction, from cmp esi, DWORD PTR [eax+4] to cmp DWORD PTR [eax+4], esi, but (again) this is utterly irrelevant.

    Bottom line: no, you're not likely to gain anything from manually hoisting the code out of the loop with a modern compiler (at least with optimization enabled -- I was using /O2b2 with VC++ and /O3 with g++; comparing optimization with optimization turned off seems pretty pointless to me).

提交回复
热议问题