Skip to content
Advertisement

What is better: multiple “if” statements or one “if” with multiple conditions?

For my work I have to develop a small Java application that parses very large XML files (~300k lines) to select very specific data (using Pattern), so I’m trying to optimize it a little. I was wondering what was better between these 2 snippets:

if (boolean_condition && matcher.find(string)) {
    ...
}

OR

if (boolean_condition) {
    if (matcher.find(string)) {
        ...
    }
}

Other details:

  • These if statements are executed on each iteration inside a loop (~20k iterations)
  • The boolean_condition is a boolean calculated on each iteration using an external function
  • If the boolean is set to false, I don’t need to test the regular expression for matches

Thanks for your help.

Advertisement

Answer

One golden rule I follow is to “Avoid Nesting” as much as I can. But if it is at the cost of making my single if condition too complex, I don’t mind nesting it out.

Besides you’re using the short-circuit && operator. So if the boolean is false, it won’t even try matching!

So,

if (boolean_condition && matcher.find(string)) {
    ...
}

is the way to go!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement