Category Archives: Performance

The Elvis (conditional null) operator is not magic

I was looking over somebody else’s code the other day and was intrigued by the liberal use of the Elvis or correctly known as, conditional null operator, i.e. the ?.

I assumed that for every ?. the compiler would create an IF statement, but it did make me wonder whether the compiler was actually able to optimize such code (where the ?. is used multiple times on the same object), so for example, what’s produced in IL for the following

var s = ??? // null or an instance 
Console.WriteLine(s?.Name?.Length);
Console.WriteLine(s?.Name);

My assumption would be that (without any optimization) we’d end up with the following

Console.WriteLine(s != null ? (s.Name != null ? s.Name.Length : 0) : 0);
Console.WriteLine(s != null ? s.Name : null);

Or, would if magically create code like this

object o = null;
int? l = null;

if (s != null)
{
   o = s.Name;
   if (s.Name != null)
   {
      l = s.Name.Length;
   }
}

Console.WriteLine(l);
Console.WriteLine(o);

With the first snippet of code, a best case scenario results in the IF statement being called twice (when s is null), the worst case (when nothing is null) is that the IF statement will be called three times. Whereas the second example would have the IF called once (when s is null) and twice in the worst case (when nothing is null).

Ofcourse the easiest way to see what happens is to fire up ILSpy and take a look at the generated IL/C# code. Here’s the C# that ILSpy created for us based upon the IL

object obj;
if (s == null)
{
   obj = null;
}
else
{
   string name = s.Name;
   obj = ((name != null) ? new int?(name.Length) : null);
}
Console.WriteLine((int?)obj);
Console.WriteLine((s != null) ? s.Name : null);

In this code, the best case (when s is null), the IF statement is called twice and worst case (when nothing is null), it’s called three times.

This is a simple example, but it’s worth being aware of what code is being produced using such syntactic sugar.