Should we still be optimizing “in the small”?

后端 未结 22 2106
旧时难觅i
旧时难觅i 2020-12-05 11:32

I was changing my for loop to increment using ++i instead of i++ and got to thinking, is this really necessary anymore? Surely today\'s compilers

22条回答
  •  爱一瞬间的悲伤
    2020-12-05 11:59

    One also needs to be careful that changing from pre/post- increment/decrement operators doesn't introduce an undesirable side effect. For example, if you're iterating over a loop 5 times simply to run a set of code multiple times without any interest in the loop index value, you're probably okay (YMMV). On the other hand if you do access the loop index value than the result may not be what you expect:

    #include 
    
    int main()
    {
      for (unsigned int i = 5; i != 0; i--)
        std::cout << i << std::endl;
    
      for (unsigned int i = 5; i != 0; --i)
        std::cout << "\t" << i << std::endl;
    
      for (unsigned int i = 5; i-- != 0; )
        std::cout << i << std::endl;
    
      for (unsigned int i = 5; --i != 0; )
        std::cout << "\t" << i << std::endl;
    }
    

    results in the following:

    5
    4
    3
    2
    1
            5
            4
            3
            2
            1
    4
    3
    2
    1
    0
            4
            3
            2
            1
    

    The first two cases show no difference, but notice that attempting to "optimize" the fourth case by switching to a pre-decrement operator would result in an iteration being completely lost. Admittedly this is a bit of a contrived case but I have seen this sort of loop iteration (3rd case) when going through an array in reverse order, i.e. from end to start.

提交回复
热议问题