19

Is there any difference in runtime performance between the following variable initializations?

var    x = null as object;
var    x = (object) null;
object x = null;
Kjartan
  • 18,591
  • 15
  • 71
  • 96
sharpener
  • 1,383
  • 11
  • 22
  • 36
    From Eric Lippert: _If you have two horses and you want to know which of the two is the faster_ **then race your horses.** http://ericlippert.com/2012/12/17/performance-rant/ – Soner Gönül Mar 07 '14 at 08:17
  • 8
    `var` versus `someothertype` will *never* have a runtime performance impact because `var` is a *compile* time construct. – Damien_The_Unbeliever Mar 07 '14 at 08:25
  • All of these are slower than initializing the value of x to what you want it to be anyway (which is likely the return value of a method call). – Bryan Boettcher Mar 07 '14 at 16:40
  • possible duplicate of [Will using 'var' affect performance?](http://stackoverflow.com/questions/356846/will-using-var-affect-performance) – nawfal Jul 15 '14 at 14:06

2 Answers2

51

I believe no, since there is no difference in compiled IL.

var    x = null as object;
var    x1 = (object)null;
object x2 = null;

gets compiled to

IL_0001:  ldnull      
IL_0002:  stloc.0     // x
IL_0003:  ldnull      
IL_0004:  stloc.1     // x1
IL_0005:  ldnull      
IL_0006:  stloc.2     // x2

You can see all the locals are initialized to null using ldnull opcode only, so there is no difference.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Good one, thanks! I was told once that you shouldn't initialize variables in C#. Wonder if the same holds for, e.g. `int x` vs `int x = 0`. – CompuChip Mar 07 '14 at 15:22
  • @CompuChip You can't access a un initialized local variable. are you talking about instance members? – Sriram Sakthivel Mar 07 '14 at 15:25
  • Sorry, yes obviously I was. The reason given to me being that not initializing will use something like `ldnull` to zero out the entire block, while setting it to `0` will generate explicit instructions _on top_ of that. But I would think a similar argument goes with initializing pointers to `null` which you have demonstrated as clearly false - hence the question. – CompuChip Mar 07 '14 at 15:44
  • @CompuChip [Though it is a problem before .Net2.0, it is optimized](http://blog.codinghorror.com/for-best-results-dont-initialize-variables/) – Sriram Sakthivel Mar 07 '14 at 15:47
7

First of all: No, I believe these three calls are essentially equivalent.

Secondly: Even if there was any difference between them, it would surely be so minuscule that it would be completely irrelevant in an application.

This is such a tiny piece of any program, that focusing on optimization here and in similar situations, will often be a waste of time, and might in some cases make your code more complicated for no good reason.

There is a longer interesting discussion about this on the programmers.stackexchange site.

Community
  • 1
  • 1
Kjartan
  • 18,591
  • 15
  • 71
  • 96