小编Die*_*ata的帖子

为什么在没有约束的泛型方法上将可空值类型与null进行比较会更慢?

我遇到了一个非常有趣的情况,在泛型方法中将可空类型与null进行比较比比较值类型或引用类型慢234倍.代码如下:

static bool IsNull<T>(T instance)
{
    return instance == null;
}
Run Code Online (Sandbox Code Playgroud)

执行代码是:

int? a = 0;
string b = "A";
int c = 0;

var watch = Stopwatch.StartNew();

for (int i = 0; i < 1000000; i++)
{
    var r1 = IsNull(a);
}

Console.WriteLine(watch.Elapsed.ToString());

watch.Restart();

for (int i = 0; i < 1000000; i++)
{
    var r2 = IsNull(b);
}

Console.WriteLine(watch.Elapsed.ToString());

watch.Restart();

for (int i = 0; i < 1000000; i++)
{
    var r3 = IsNull(c);
}

watch.Stop();

Console.WriteLine(watch.Elapsed.ToString());
Console.ReadKey(); …
Run Code Online (Sandbox Code Playgroud)

c# compiler-construction performance jit nullable

13
推荐指数
2
解决办法
1009
查看次数

标签 统计

c# ×1

compiler-construction ×1

jit ×1

nullable ×1

performance ×1