Is there a performance difference between int i =0 and int i = default(int)?
I was creating an integer and i wanted to instantiate it with 0 before working with.
I wrote firstly
int i = default(int);
then i removed it to replace with the other one which is
int i = 0;
I would like to know if my cho开发者_如何学编程ice is the best in mini mini performance. Will the default() function increase the instructions at compile time?
No, they are resolved at compile time and produce the same IL. Value types will be 0
(or false
if you have a bool, but that's still 0) and reference types are null
.
Marlon's answer is technically correct, but there should be a clear semantic difference between each option.
int i = 0;
Initializing to literal zero makes semantic sense when you want to do a mathematical operation on the integer, and that operation needs to start with the variable being the specific value of zero. A good example would be creating an index counter variable; you want to start with zero and count up.
int i = default(int);
Setting a variable to its default
value makes sense when you're, for example, creating a class with said variable where you know the variable will be manually set later on in the process. Here's an example (however impractical it may be):
class IntegerClass
{
private int value;
public IntegerClass(int value)
{
this.value = value;
}
public void Reset()
{
this.value = default(int);
}
}
Again, they're technically equal (and in fact will compile to identical CIL) but each provides a different semantic meaning.
Also, using default
could be required to initialize a variable when using generics.
public T SomeOperation<T>()
{
T value = default(T);
this.SomeOtherOperation(ref value);
return T;
}
The only real difference that it will make is the compile-time, so I suppose it would be a milli-milli-milli-milli second faster one way than the other when you press Debug or Compile but as soon as it's compiled, it will be exactly the same as Marlon said
These small changes will only affect your actual programming time so in a broader sense of the term, writing out default(int) is slower than writing 0 and the time you put thought into it took even longer.
精彩评论