halorox
halorox

Reputation: 37

Probability in conditional statements

Lets take a variable called someInt which might have any numeric value. We need to check if it's 0 or not.

if($someInt!=0) {
  // someInt is not 0, this is the most probable
} else {
  // someInt is 0.
}

//VS

if($someInt==0) {
  // highly unlikely... perform a jump
} else {

}

Which way is more optimal? Is there any difference (besides readability)?

Another sort of related thing I'm wondering: I have a habit of checking arrays if they any items this way:

if($myArray.length != 0) {

}
 // instead of
if($myArray.length > 0) {

}

Notice the " != ". Since array.length can only be 0 or greater than 0, is the "!=" check more optimal? I'm asking this because I've always done it this way in Visual Basic 6, it apparently worked faster there. What about other languages?

Upvotes: 2

Views: 253

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174987

Most probable conditions should be at the top. This way, the parser skips the less probable cases, and you get an overly more optimized application.

Your second question is micro-optimization. I doubt it'll make a difference one way or another in terms of performance.

Upvotes: 3

sean
sean

Reputation: 3985

For the if statement the more likely the case the higher up in the if statement you should make it, from a readability point this makes more sense and from a performance point as well. As for the array section $array.length > 0 is more readable. But, the performance shouldn't be an issue as this should not be called all that often, it is better to cache the result than it is to constantly check the array length.

Upvotes: 0

Related Questions