Akbar Badhusha
Akbar Badhusha

Reputation: 2627

Passing null to an optional parameter with default value null

I have a method that have one optional with default value null. I have observed that, those who are consuming that method are passing null as value for the optional parameter

Main Method

public void MainMethod(int id, MyClass model = null)
{
  // Logic goes here
}

There are 2 types of invocations i can see,

public void First()
{
  MainMethod(1, null);
}

public void Second()
{
  MainMethod(1);
}

Will both of them will be having same performance? Or is one better than another one?

Upvotes: 1

Views: 3915

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499730

They will both result in the exact same IL. In Second, the compiler just provides the argument for you automatically.

Defaults are always applied by the compiler at the call site (the piece of code calling the method). That has various downsides - particularly in terms of handling changes to the default value - but it does make it easy to reason about performance etc.

Upvotes: 7

Ahmed Msaouri
Ahmed Msaouri

Reputation: 316

I think calling the MainMethod (1) with default value is a little faster, when we pass a parameter that is null it is necessary to check if it is one to assign the null value again.`

I have executed the calls in a loop to calculate the execution time and this is the result:

        TimeSpan stop;
        TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
        for (int i = 0; i < 10000; i++)
        {
             MainMethod(1, null);
        }
        
        stop = new TimeSpan(DateTime.Now.Ticks);

        TimeSpan stop2;
        TimeSpan start2 = new TimeSpan(DateTime.Now.Ticks);
        for (int i = 0; i < 10000; i++)
        {
            MainMethod(1);
        }

        stop2 = new TimeSpan(DateTime.Now.Ticks);
        Console.WriteLine(stop.Subtract(start).TotalMilliseconds);
        Console.WriteLine(stop2.Subtract(start2).TotalMilliseconds);



        public static void MainMethod(int id, MyClass model = null)
        {
            if (model == null)
            {
                Console.WriteLine("Is null");
            }
            else
            {
                Console.WriteLine("Is Not null");
            }
        }

result

call MainMethod(1): 7996,862 ms

call MainMethod(1, null): 848,0054 ms

Upvotes: -3

Related Questions