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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With