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!
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.
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.
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.
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;
}
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