Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is conditional initialization handled and is it a good practice?

I am trying to decide between several possible practices. Say, my function has a number of if() blocks, that work on data, that is unique to them.

  • Should I declare and initialize the local (for the block) data inside the block? Does this have runtime performance cost (due to runtime allocation in the stack)?

  • Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block?

  • Or should I seperate the if() blocks in different functions, even though they are only a couple of lines long and used only one in the program?

Or am I ovelooking another, cleaner, option? Is the question even answerable in it's current, general form?

like image 556
Vorac Avatar asked Apr 19 '13 10:04

Vorac


2 Answers

Should I declare and initialize the local (for the block) data inside the block?

Absolutely: this tends to make programs more readable.

Does this have runtime performance cost (due to runtime allocation in the stack)?

No: all allocations are done upfront - the space on the stack is reserved for variables in all branches upon entering a function, not when the branch is entered. Moreover, this could even save you some space, because the space allocated for variables in non-overlapping branches can be reused by the compiler.

Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block?

No, this is not faster, and could be slightly more wasteful.

Or should I seperate the if() blocks in different functions, even though they are only a couple of lines long and used only one in the program?

That would probably have a negative impact on readability of your program.

like image 140
Sergey Kalinichenko Avatar answered Nov 11 '22 20:11

Sergey Kalinichenko


It's a good practice to keep the scope of the variable as small as possible.
If you declare all the variable one time at the beginning, and you don't use
them often in your program. It's no use, it takes more memory.

Also, another advantages of keeping the scope small is that you can reuse
the same names again. (you don't have to invent new names each time you
do something trivial).

like image 41
mohit Avatar answered Nov 11 '22 20:11

mohit