Fun With the ?? Operator in C#: if { } or ?? – Which is Faster?

Yesterday evening at work a team member and I were pair programming.  We had a disagreement about how to code a few lines.  The question was around whether to use the ?? operator or to use an if statement using String.IsNullOrEmpty.  We settled it like most developers do and that is with a benchmark.  Here’s the fun we had.

To give you an idea as to what we were doing here’s some context.  We had a function that took an object.  We wanted to add extra context data to the object, but only if the object didn’t have it set.  In other words, the data may have already been set somewhere else in the application and we didn’t want to override what was already set.  There were two ways to do this and since I was typing I started typing the following.

private void AddContextData(LogEntry entry)
{
entry.Url = entry.Url ?? HttpContext.Current.Request.Url.ToString();
entry.UserIpAddress = entry.UserIpAddress ?? HttpContext.Current.Request.UserHostAddress;
entry.UserName = entry.UserName ?? HttpContext.Current.User.Identity.Name;
}

My pairing partner started in on me immediately.  He was thinking it should be written like this.

private void AddContextData(LogEntry entry)
{
if (String.IsNullOrEmpty(entry.Url)) entry.Url = Context.Current.Request.Url.ToString();
if (String.IsNullOrEmpty(entry.UserIpAddress)) entry.UserIpAddress = HttpContext.Current.Request.UserHostAddress;
if (String.IsNullOrEmpty(entry.UserName)) = entry.UserName = HttpContext.Current.User.Identity.Name;
}

The ?? for those that aren’t familiar with it is called the “null coalescing” operator. Scott Gu wrote about it late 2007 if you want some additional information and samples.  It is a fun little operator and can save you a lot of typing in more places than you think.  Most developers though don’t think to use it and instead code the long handed version doing a check using a if block. 

In the end we decided to settle our disagreement and go with the one that was the fastest.  Thus we whipped up a quick benchmark to test one vs. the other.  Here’s the benchmark code for both samples.

?? Operator Benchmark Code

string x = "foo bar";
Stopwatch watch = new Stopwatch();
long ticks = watch.Time(() => x = x ?? "bar foo", 100000);
textBox1.Text += "??: " + ticks.ToString() + Environment.NewLine;

Note: If you copy the above code, it will not work on your machine unless you have a Time() extension method as part of your arsenal. 

if { } Benchmark Code

string x = "foo bar";
Stopwatch watch = new Stopwatch();
long ticks = watch.Time(() =>
{
if (String.IsNullOrEmpty(x))
{
x = "bar";
}
}
, 100000);
textBox1.Text += "if: " + ticks.ToString() + Environment.NewLine;

The Results

The results were not all that exciting. Really it only proved there was wasn’t any difference in speed, if anything giving a very very slight edge to the ?? operator.  At any rate it was a fun side bar to end the evening.  Happy null coalescing!

 

References
0

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Liam Knox replied on Fri, 2009/08/07 - 6:49pm

The question should never be around a micro performance difference rather on which reads easier. I would guess before there trial you would of known that there would be relatively no difference in the two. In this instance I would punt for ?? for clarity , though I think there are other aspects such as non immutability that you could consider greater concerns in your code

Travis lastname replied on Mon, 2009/08/10 - 5:23pm in response to: knoxl

and this attitude my friends is why we are forced to work with a *extremely* bloated slow pig of an operating system, and the sole reason I am forced to upgrade my hardware ever other year...

cerberis cerbas replied on Tue, 2009/08/11 - 1:33am

string.IsNullOrEmpty returns different result than operator ??.

when string is empty, operator ?? returns false :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.