Does Performing a Null Check on a Generic Cause Boxing? [duplicate]

南楼画角 提交于 2020-01-12 18:50:57

问题


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 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.

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.


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/48685875/does-performing-a-null-check-on-a-generic-cause-boxing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!