Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will declaring variables inside sub-blocks improve performance?

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
}
}
like image 229
CJ7 Avatar asked Aug 04 '10 03:08

CJ7


People also ask

Is it okay to declare variables inside a loop?

In short, you are right to do it. Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time.

What happens if you declare a variable inside a loop?

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

Can a variable be a for loop?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure. A loop variable is a classical fixture in programming that helps computers to handle repeated instructions.


2 Answers

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.

like image 195
Mark Cidade Avatar answered Sep 28 '22 06:09

Mark Cidade


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.

like image 22
Justin Niessner Avatar answered Sep 28 '22 04:09

Justin Niessner