Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
3rgo Avatar asked Mar 10 '11 13:03

3rgo


People also ask

What is better than multiple if statements?

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.

Is it bad to have multiple if statements?

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.

How do you handle multiple if conditions?

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.

What is the difference between multiple if statements and else if?

If statements are executed independent of one another; each one will run. Else if statements only execute if the previous if s fail.


2 Answers

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!

like image 84
adarshr Avatar answered Oct 02 '22 14:10

adarshr


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).

like image 24
Jonathan Avatar answered Oct 02 '22 14:10

Jonathan