Generic vs not-generic performance in C#

后端 未结 8 1591
旧巷少年郎
旧巷少年郎 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:44

    Two things:

    1. You are benchmarking with DateTime.Now. Use Stopwatch instead.
    2. You are running code that is not under normal circumstances. JIT is most likely affecting the first run, making your first method slower.

    If you switch the order of your tests (i.e. test the non-generic method first), does your result reverse? I would suspect so. When I plugged your code into LINQPad, and then copied it so that it ran both tests twice, the execution times for the second iteration were within a few hundred ticks of each other.

    So, in answer to your question: yes, someone knows why. It's because your benchmark is inaccurate!

提交回复
热议问题