user2101976
user2101976

Reputation:

Does giving arguments with (new or declaring new variable) has difference in ram usage?

I was programming the other day and I was curious as to whether or not

giving arguments with new

Application.Run(new Form1());

or declaring new variable

Form1 form1 = new Form1();
Application.Run(form1);

has difference in ram usage, speed, ...etc

Do they differ from another?

Upvotes: 2

Views: 73

Answers (3)

ths
ths

Reputation: 2942

The difference is that in the case of

Application.Run(new Form1());

the Form1 object is only in scope of the Run call and eligible for garbage collection immediately after.

Whereas with

Form1 form1 = new Form1();
Application.Run(form1);

the form1 is still in scope after the Run and can't be GC'd until the end of the block. This can (probably not in this case, but for other objects) have quite an impact of runtime memory usage.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117084

Yes, there is a difference.

I defined this method to show the difference:

public string Run(string param)
{
    return param + "!";
}

I then called it these two ways:

(1)

    var text = "Hello";
    Console.WriteLine(Run(text));

(2)

    Console.WriteLine(Run("Hello"));

The first produces this IL:

IL_0000:  nop         
IL_0001:  ldstr       "Hello"
IL_0006:  stloc.0     // text
IL_0007:  ldarg.0     
IL_0008:  ldloc.0     // text
IL_0009:  call        Run
IL_000E:  call        System.Console.WriteLine
IL_0013:  nop         
IL_0014:  ret    

The second produces this IL:

IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  ldstr       "Hello"
IL_0007:  call        Run
IL_000C:  call        System.Console.WriteLine
IL_0011:  nop         
IL_0012:  ret   

The difference is the IL stloc.0. The first method allocates storage for the text variable prior to the call. The second method doesn't.

The difference is very very minor though.

The optimized code for each are:

(1)

IL_0000:  ldstr       "Hello"
IL_0005:  stloc.0     // text
IL_0006:  ldarg.0     
IL_0007:  ldloc.0     // text
IL_0008:  call        Run
IL_000D:  call        System.Console.WriteLine
IL_0012:  ret    

(2)

IL_0000:  ldarg.0     
IL_0001:  ldstr       "Hello"
IL_0006:  call        Run
IL_000B:  call        System.Console.WriteLine
IL_0010:  ret  

Still the same change in storage - just less nops.

Upvotes: 4

Artyom
Artyom

Reputation: 3571

No there is no difference. Application.Run(..) method can hold the reference to the Form instance. So GC does not utilize this. It doesn't matter if you declare form1 variable or not as the reference to it is lost when the method ends execution.

Upvotes: -2

Related Questions