C for loop indexing: is forward-indexing faster in new CPUs?

后端 未结 7 2052
抹茶落季
抹茶落季 2020-12-01 09:57

On a mailing list I\'m subscribed to, two fairly knowledgeable (IMO) programmers were discussing some optimized code, and saying something along the lines of:

相关标签:
7条回答
  • 2020-12-01 10:23

    No, we can't say that CPU implementations have changed to make forward looping faster. And that has very little to do with the CPUs themselves.

    It has to do with the fact that you haven't specified which CPU you're talking about, nor which compiler.

    You cannot ask a blanket question about CPU issues with the C tag and expect to get an intelligent answer simply because nothing in the C standard mandates how fast CPU s should be at various operations.

    If you'd like to rephrase your question to target a specific CPU and machine language (since what machine language you get out of a C compiler depends entirely on the compiler), you may get a better answer.

    In either case, it shouldn't matter. You should be relying on the fact that the people that wrote your compiler know a great deal more than you about how to eke the last inch of performance from the various CPUs.

    The direction in which you should be iterating has always been dictated by what you have to do. For example, if you have to process array elements in ascending order, you use:

    for (i = 0; i < 1000; i++) { process (a[i]); }
    

    rather than:

    for (i = 999; i >= 0; i--) { process (a[999-i]); }
    

    simply because any advantage you may gain in going backwards is more than swamped by the extra calculations on i. It may well be that a naked loop (no work done in the body) may be faster in one direction than another but, if you have such a naked loop, it's not doing any real work anyway.

    As an aside, it may well be that both those loops above will come down to the same machine code anyway. I've seen some of the code put out by the GCC optimizer and it made my head spin. Compiler writers are, in my opinion, a species alone when it comes to insane levels of optimization.

    My advice: always program for readability first then target any specific performance problems you have ("get it working first, then get it working fast").

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