Question

In C#, would there be any difference in performance when comparing the following THREE alternatives?

ONE

void ONE(int x) {

if (x == 10) 
{
    int y = 20;
    int z = 30;
    // do other stuff
} else {
    // do other stuff
}
}

TWO

void TWO(int x) {

int y;
int z;

if (x == 10) 
{
    y = 20;
    z = 30;
    // do other stuff
} else {
    // do other stuff
}
}

THREE

void THREE(int x) {

int y = 20;
int z = 30;

if (x == 10) 
{
    // do other stuff
} else {
    // do other stuff
}
}
Was it helpful?

Solution

All else being equal (and they usually aren't, which is why you normally have to actually test it), ONE() and TWO() should generate the same IL instructions since local variables end up scoped to the whole method. THREE() will be negligibly slower if x==10 since the other two won't bother to store the values in the local variables.

All three take up the same amount of memory—the memory for all variables is allocated even if nothing is stored in them. The JIT compiler may perform an optimization here, though, if it ever looks for unused variables.

OTHER TIPS

There no performance difference, but you're going to find variable scope issues between each of those examples.

You're also showing three different intents between those examples, which isn't what you want:

  1. y and z are limited to the scope of the if statement.

  2. y and z are used outside of the if statement, but are set conditionally.

  3. y and z have nothing to do with the if statement whatsoever.

Of course, you should always pick ONE, it is much more readable. That it is faster by a fraction of a nanosecond isn't an accident, readable code often is.

I don't think it'll make much difference. The only time you would need to worry is if creating the new object and initializing it is expensive. You could always try to profile each method a couple thousand times to see if there are any differences but I doubt you'll find any.

The only time I move a declaration further away from where it's used is if it'll be worked on in a loop. e.g.:

void RunMethod() {
  FormRepresentation formRep = null;
  for (int idx = 0; idx < 10; idx++) {
    formRep = new FormRepresentation();
    // do something
  }
}

It doesn't actually make any difference since the object is still being created but, to me, it looks cleaner. The other thing you need to consider is the scope of the variable. Declared variables cannot be used outside the scope they were declared in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top