Whether pattern matching is preferred over benchmark or value equality

I see many examples of how to use pattern matching in C # 7. Everything looks good. However, I have a question that I cannot seem to find an answer to.

Let's say you have the following expression:

if (a is null)

      

My question is, is it preferable to use pattern matching instead of reference or value equality since C # 7?

So instead of writing:

if (a == null)

      

or

if (a.Equals(null))

      

or

if (object.Equals(a, null))

      

I suspect it a is null

generates something like the last expression. But would it be generally preferable to switch to pattern matching?

Correct me if I am wrong and this is a opinion based question primarily, but I could not find a definitive answer that would support this.

+3


source to share


1 answer


Consider the following four pieces of code:

// 1
var x = "";
var y = x is null;

// 2
var x = "";
var y = x.Equals(null);

// 3
var x = "";
var y = object.Equals(x, null);

// 4
var x = "";
var y = x == null;

      

IL for them, respectively, is:



// 1
IL_0001: ldstr ""
IL_0006: stloc.0
IL_0007: ldnull
IL_0008: ldloc.0
IL_0009: call bool [mscorlib]System.Object::Equals(object, object)
IL_000e: stloc.1

// 2
IL_0001: ldstr ""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: call bool [mscorlib]System.Object::Equals(object, object)
IL_000e: stloc.1

// 3 
IL_0001: ldstr ""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: call bool [mscorlib]System.Object::Equals(object, object)
IL_000e: stloc.1

// 4
IL_0001: ldstr ""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: ceq
IL_000b: stloc.1

      

As you can see, the first three results match the identical code. The version ==

uses ceq

instead of .Equals()

.

I guess it ceq

is faster, and thus x == null

the fastest way to test for null

. Beyond that, it becomes a matter of preferred style.

+1


source







All Articles