简体   繁体   中英

Which one gives me better performance in variables declaration?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM