是否对常规原因装箱执行Null检查? [英] Does Performing a Null Check on a Generic Cause Boxing?

查看:45
本文介绍了是否对常规原因装箱执行Null检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,找不到答案.说我有这段代码:

I looked around for this and could not find an answer. Say I have this code:

class Command<T> : ICommand<T>
{
    public void Execute(T parameter)
    {
        var isNull = parameter == null;
        // ...
    }
}

T 可以是任何类,甚至可以是 Nullable<> .如果 T 是值类型,执行上述检查是否会引起装箱?我的理解是,这与调用 ReferenceEquals 相同,后者需要两个 object 参数,如果 T 是值类型,则这两个参数都会导致装箱,如果我理解正确的话.

T could be any class, even a Nullable<>. Does performing the check above cause boxing if T is a value type? My understanding is that this is the same as calling ReferenceEquals which takes two object arguments, either of which would cause boxing if T was a value type, if I understand correctly.

如果上述情况确实导致装箱,是否有更优选的方式来执行装箱而不导致装箱?我知道有 default(T),但是在 int 0 的情况下,我正在查看此值是否为 null ,无需装箱.另外,我正在寻找一种同时满足值和引用类型的方法.

If the above does cause boxing, is there a more preferred way to do this without causing the box to occur? I know there is default(T) but in the case of int that is 0, and I am looking to see if this value is null without boxing it. Also, I am looking to do this in a way that satisfies both value and reference types.

推荐答案

否-至少在我看来不是.如果 T 是不可为空的值类型,则JIT编译器将有效地将 parameter == null 检查替换为 false .没有执行时间检查.

No - at least not in my understanding. If T is a non-nullable value type, the parameter == null check is effectively replaced with false by the JIT compiler; no execution-time check is performed.

这是只有JIT编译器才能执行的优化,因为C#编译器仅生成一种形式的代码.例如,为您的样本生成的IL为:

This is an optimization that only the JIT-compiler can perform, as the C# compiler only generates one form of code. For example, the IL generated for your sample is:

IL_0000:  ldarg.1
IL_0001:  box        !T
IL_0006:  ldnull
IL_0007:  ceq

这似乎实际上是在执行装箱操作-但我相信一个不错的JIT编译器会发现,当 T 是不可空的时, ceq 总是给出错误的结果,然后删除box操作.

That would appear to actually perform the boxing - but I trust a decent JIT compiler to spot that when T is non-nullable, the ceq will always give a false result, and remove the box operation.

这篇关于是否对常规原因装箱执行Null检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆