Which one gives me better performance in variables declaration?

70 views Asked by At

I need to know which one of the following examples gives me higher performance?

Object O = someValue;
if (condition){
    //statements
    //statements
} else {
    //statements
    //statements
}

Or

Object O;
if (condition){
    O = someValue;
    //statements
    //statements
} else {
    O = someValue;
    //statements
    //statements
}

Or

if (condition){
    Object O = someValue;
    //statements
    //statements
} else {
    Object O = someValue;
    //statements
    //statements
}

NOTE: someValue is equal in all cases

2

There are 2 answers

0
Pavan Kumar On BEST ANSWER

Compilers are smart enough to analyze and identify the best way to initialize. But as a coding practice, first one would be preferred and below are the downsides of second and third.

Second way just increases the lines of code. If you need to modify the someValue in future, you (or someone who maintains the code) need to modify in two places. If the if block is long enough, we might miss out modifying the else block causing error situations.

Third way just initializes the variable inside the conditional blocks and are accessible only inside the blocks. To my understanding, even compiler might not optimize the initialization by moving it out of the conditional statements. This again suffers from problem of second approach. Also, the variables initialized within the conditional blocks are not accessible outside, so if you need to print / log the object outside the if/else block, its not allowed.

One more fact: Java coding conventions do not recommend using variable names beginning with a capital character.

2
Aditya Sundaramurthy On

The first representation would be most optimal. That said, most modern compilers including JavaC optimizes the byte code to reduce or eliminate unnecessary initialization. You can check this with tools like javap or your favorite bytecode analyzer.

This applies to most compilers, not just Java.