Question:i just want to ask 2 question, if i write 2 below codes in java then which one is faster in terms of cpu cycles and why? Someone told me that 1st option is not correct in terms of cpu cycle because in that 2 conditions are checked i.e if and !
boolean flag = true;
//OPTION ONE
if(!flag) {
//error
} else {
//got the answer
}
//OPTION TWO
if(flag) {
//got the answer
} else {
//error
}
There is no practical difference on a modern JVM implementation.
The compiler will do the right thing, don’t worry about it. In fact, if it can prove that flag always has a constant value of true at compile time it will eliminate the check and the unreachable branch entirely.