Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance difference between int i =0 and int i = default(int)?

Tags:

c#

.net

c#-4.0

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 choice is the best in mini mini performance. Will the default() function increase the instructions at compile time?

like image 778
Samidjo Avatar asked Dec 03 '22 07:12

Samidjo


2 Answers

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.

like image 104
Marlon Avatar answered Mar 16 '23 00:03

Marlon


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;
}
like image 30
Adam Maras Avatar answered Mar 15 '23 23:03

Adam Maras