Generic vs not-generic performance in C#

后端 未结 8 1609
旧巷少年郎
旧巷少年郎 2020-12-25 13:21

I\'ve written two equivalent methods:

static bool F(T a, T b) where T : class
{
    return a == b;
}

static bool F2(A a, A b)
{
    return a == b;
         


        
8条回答
  •  渐次进展
    2020-12-25 13:37

    I've done performance analysis in a professional capacity several times in my career, and have a couple of observations.

    • First, the test is way too short to be valid. My rule of thumb is that a performance test should run for 30 minutes or so.
    • Second, it's important to run the test many times, to get a range of timings.
    • Third, I'm surprised the compiler didn't optimize away the loops, since the function results are not used and the functions being called have no side effects.
    • Fourth, micro benchmarks are often misleading.

    I once worked on a compiler team that had a big audacious performance goal. One build introduced an optimization that eliminated several instructions for a particular sequence. It should have improved performance, but instead the performance of one benchmark fell dramatically. We were running on hardware with a direct mapped cache. It turns out that the code for the loop and the function called in the inner loop occupied the same cache line with the new optimization in place, but did not with the prior generated code. In other words, that benchmark was really a memory benchmark, and entirely dependent on memory cache hits and misses, whereas the authors thought they had written a computational benchmark.

提交回复
热议问题