Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poor performance of many if-else statements in Java

I have a method that checks all of the combinations of 5 different conditions with 32 if-else statements (think of the truth table). The 5 different letters represent methods that each run their own regular expressions on a string, and return a boolean indicating whether or not the string matches the regex. For example:

if(A,B,C,D,E){

}else if(A,B,C,D,!E){

}else if(A,B,C,!D,!E){

}...etc,etc.

However, it is really affecting the performance of my application (sorry, I can't go into too many details). Can anyone recommend a better way to handle such logic?

Each method using a regular expression looks like this:

String re1 = "regex here";
Pattern p = Pattern.compile(re1, Pattern.DOTALL);
Matcher m = p.matcher(value);
return m.find();

Thanks!

like image 987
littleK Avatar asked Oct 25 '11 15:10

littleK


People also ask

Do many if statements slow down code?

YES. I say this considering a Worst case scenario, in this case a very large model object with lots of conditions. Here, the code has to go through all conditional checking which eventually slows down the code.

Does if-else affect performance?

If-else statements optimization Based on these conditions, we determine some lines of code to execute. Unfortunately, using too many if-else conditional statements can affect performance because the Java virtual machine will have to compare the conditions.

How do you handle multiple If statements in Java?

We can either use one condition or multiple conditions, but the result should always be a boolean. When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.


1 Answers

You can try

boolean a,b,c,d,e;
int combination = (a?16:0) + (b?8:0) + (c?4:0) + (d?2:0) + (e?1:0);
switch(combination) {
   case 0:
        break;
   // through to
   case 31:
        break;
}
like image 114
Peter Lawrey Avatar answered Sep 20 '22 01:09

Peter Lawrey