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

前端 未结 3 893
温柔的废话
温柔的废话 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:58

    I love performance testing and I love fast programs so I admire your question.

    I tried to reproduce your findings and failed. On my Intel i7 x64 system running your code samples on .NET4 framework in the x86|Release configuration, all four test cases produced roughly the same timings.

    To do the test I created a brand new console application project and used the QueryPerformanceCounter API call to get a high-resolution CPU-based timer. I tried two settings for jmax:

    • jmax = 1000
    • jmax = 1000000

    because locality of the array can often make a big difference in how the performance behaves and the size of the of loop increases. However, both array sizes behaved the same in my tests.

    I have done a lot of performance optimization and one of the things that I have learned is that you can very easily optimize an application so that it runs faster on one particular computer while inadvertently causing it to run slower on another computer.

    I am not talking hypothetically here. I have tweaked inner loops and poured hours and days of work to make a program run faster, only to have my hopes dashed because I was optimizing it on my workstation and the target computer was a different model of Intel processor.

    So the moral of this story is:

    • Code snippet (2) runs faster than code snippet (3) on your computer but not on my computer

    This is why some compilers have special optimization switches for different processors or some applications come in different versions even though one version could easily run on all supported hardware.

    So if you are going to do testing like this, you have to do it same way that JIT compiler writers do: you have to perform your tests on a wide variety of hardware and then choose a blend, a happy-medium that gives the best performance on the most ubiquitous hardware.

提交回复
热议问题