C# generated IL for ++ operator - when and why prefix/postfix notation is faster

前端 未结 3 841
温柔的废话
温柔的废话 2021-02-04 02:41

Since this question is about the increment operator and speed differences with prefix/postfix notation, I will describe the question very carefully lest Eric Lippert discover it

3条回答
  •  攒了一身酷
    2021-02-04 02:59

    OK after much research (sad I know!), I think have answered my own question:

    The answer is Maybe. Apparently the JIT compilers do look for patterns (see http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx) to decide when and how array bounds checking can be optimized but whether it is the same pattern I was guessing at or not I don't know.

    In this case, it is a moot point because the relative speed increase of (2) was due to something more than that. Turns out that the x64 JIT compiler is clever enough to work out whether an array length is constant (and seemingly also a multiple of the number of unrolls in a loop): So the code was only bounds checking at the end of each iteration and the each unroll became just:-

            total += intArray[j]; j++;
    00000081 8B 44 0B 10          mov         eax,dword ptr [rbx+rcx+10h] 
    00000085 03 F0                add         esi,eax 
    

    I proved this by changing the app to let the array size be specified on the command line and seeing the different assembler output.

    Other things discovered during this excercise:-

    • For a standalone increment operation (ie the result is not used), there is no difference in speed between prefix/postfix.
    • When an increment operation is used in an indexer, the assembler shows that prefix notation is slightly more efficient (and so close in the the original case that I assumed it was just a timing discrepency and called them equal - my mistake). The difference is more pronounced when compiled as x86.
    • Loop unrolling does work. Compared to a standard loop with array bounds optimization, 4 rollups always gave an improvement of 10%-20% (and the x64/constant case 34%). Increasing the number of rollups gave varied timing with some very much slower in the case of a postfix in the indexer, so I'll stick with 4 if unrolling and only change that after extensive timing for a specific case.

提交回复
热议问题