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:
boolean_condition
is a boolean
calculated on each iteration using an external functionboolean
is set to false
, I don't need to test the regular expression for matchesThanks for your help.
Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.
In this case it is fine, in fact in most cases it is. The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
If statements are executed independent of one another; each one will run. Else if statements only execute if the previous if s fail.
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!
The following two methods:
public void oneIf(boolean a, boolean b) { if (a && b) { } } public void twoIfs(boolean a, boolean b) { if (a) { if (b) { } } }
produce the exact same byte code for the method body so there won't be any performance difference meaning it is purely a stylistic matter which you use (personally I prefer the first style).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With