Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would lots of unnecessary variables cause performance issues in C#?

I have a C# 4.0 application and inside this application I have lots of unnecessary variables. Like _foo variable inside the below code:

public string Foo() { 
    var _foo = "foo bar";
    return _foo;
}

As I mentioned, situations like this one occur inside lots of methods.

Would lots of unnecessary variables (like the ones I explained in this case) cause performance problem in C#?

Edit:

I am not asking any advice if I should remove them or not. My question is all about performance effect. In fact, the app is not written by me and I am new to this project. I just saw and wonder if it has any perf. effect besides the fact that it has a effect on the quality of the code.

like image 334
tugberk Avatar asked Jan 26 '12 13:01

tugberk


1 Answers

Would lots of unnecessary variables (like the ones I explained in this case) cause performance problem in C#?

No, they won't.

The compiler is intelligent enough to remove all the unnecessary stuff when you compile in Release mode and optimize your code to:

public string Foo()
{
    return "foo bar";
}

or more precisely to:

.method public hidebysig instance string Foo() cil managed
{
    .maxstack 1
    .locals init (
        [0] string str)
    L_0000: ldstr "foo bar"
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: ret 
}

which when compared to its Debug mode counterpart is quite different:

.method public hidebysig instance string Foo() cil managed
{
    .maxstack 1
    .locals init (
        [0] string _foo,
        [1] string CS$1$0000)
    L_0000: nop 
    L_0001: ldstr "foo bar"
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: stloc.1 
    L_0009: br.s L_000b
    L_000b: ldloc.1 
    L_000c: ret 
}

It's definitely not something that you should worry about from a performance point of view. What you should worry about is readability of your code and this optimized code example seems far more readable than your version.

So you could trust the compiler which is constantly improving and is able to optimize such situations.

like image 95
Darin Dimitrov Avatar answered Sep 20 '22 15:09

Darin Dimitrov