Java: How/Should I optimize a method with multiple IF statements?
It is absolutely crucial for dev to see the real-time dynamics and each millisecond matter a lot.
That's it. Unless your devs can read many thousand messages per second, you're fine. The cost of
if (optionalA) {
sb.append("something");
}
consists of two parts.
- The conditional branch and the appending. A mispredicted branch takes 10-20 cycles, i.e., up to
20 / 3
nanoseconds on a 3 GHz CPU. A correctly predicted branch is essentially free and because of the boolean being constant and the code being hot, you can assume that. - According to the length of
"something"
, the appending may be more costly, but no details are given, so there's nothing to optimize.
I don't think the JIT will find something to optimize here. You could size your StringBuilder
to gain a bit.
All in all, it is premature optimization.
Imagine this code being translated in JavaScript (by GWT)
Modern browsers have an advanced JIT just like Java does. Due to Javascript being weakly typed, it can't be as fast, but it comes pretty close.
Measure before optimizing, so you don't spend your time where the CPU does not.
What is the best way to optimize a function with many if-else statements(multiple conditions)?
You might want to look into Guava's RangeMap
classes (other similar implementations are available).
These allow you to express these conditions something like this:
RangeMap<Integer, String> rangeMap =
ImmutableRangeMap.<Integer, String>builder()
.put(Range.closed(90702, 90733), "AC")
.put(Range.closed(10004, 10037), "AC")
.put(Range.closed(10087, 10108), "EN")
.put(Range.closed(10004, 10037), "AC")
// ...
.build();
Construct this once, and then query it like:
String major = rangeMap.get(crmCompare);
There are a couple of advantage of this:
- It's a more compact syntax
- The creation of the ranges is validated, both for min and max being in the correct order, and for not overlapping.
The disadvantage is the addition of Guava, if you're not already using it.
Multiple if conditions ,how to optimize it
Say you have a property file with
do1=val1,val2,val3
do2=val5,val6,val7
(it seems you have a fixed set of actions)
You may load it with
HashMap<String, HashSet<String>> rules = new HashMap<String, HashSet<String>>();
for(String key : properties.stringPropertyNames()) {
HashSet<String> set = new HashSet<String>();
set.addAll(Arrays.asList(properties.getProperty(key).split(",")));
rules.put(key, set);
}
Now you have a map linking action names ("do1", etc.) to sets of possible values ("val1", etc.).
You may execute the rules with
if (rules.get("do1").contains(parameter)) do1();
if (rules.get("do2").contains(parameter)) do2();
(I let you add the necessary checks to avoid null pointer exceptions for example)
How to replace multiple if-else statements to optimize code?
This wont stop you code from doing many String#contains
calls, however, it will avoid the if/else
chaining..
You can create a key-function map and then iterate over the entries of this map to find which method to call.
public void one() {...}
public void two() {...}
private final Map<String, Runnable> lookup = new HashMap<String, Runnable>() {{
put("one", this::one);
put("two", this::two);
}};
You can then iterate over the entry-set:
for(final String s : array) {
for(final Map.Entry<String, Runnable> entry : lookup) {
if (s.contains(entry.getKey())) {
entry.getValue().run();
break;
}
}
}
Optimize the several multiple OR conditions in IF statement
Here's one way: define a Set<String>
with the possible username values before the if
block, and check against it. Notice how all the strings were lower-cased to avoid trouble:
Set<String> userNames = new HashSet<>();
userNames.add("def_username");
userNames.add("ghi_username");
userNames.add("jkl_username");
userNames.add("mno_username");
userNames.add("pqr_username");
userNames.add("stu_username");
userNames.add("vwx_username");
// assuming `user` is non-null
user = user.trim().toLowerCase();
if (user.equals("abc_username")) {
verifyXYZPermission(Folder);
verifyNoPermissionToDelete();
} else if (userNames.contains(user)) {
if (user.equals("ghi_username")) {
verifyNoPermissionToCreate(user, Folder, level2);
verifyNoPermissionToUpdate(Folder);
} else {
verifyCreatePermission(level2);
verifyPermisssionToUpdate(Folder);
}
}
Related Topics
Spring-Data-Jpa Repository - Underscore on Entity Column Name
How to Retrieve Element Value from Soap Response Using Java
Refreshing Existing Windows in Java Swing
Why How to Declare a Variable Without an Initial Value
How to Write Unit Test for a Setter Method Which Does Not Have a Getter Method
Using Comparable to Compare Generic Variables
How to Sort Arraylist of Objects by Timestamp and Get Last Five Elements
How to Know Which Tomcat Version Embedded in Spring Boot
How to Write New Line Character to a File in Java
How to Autowire a Component Which Is Having Constructor With Arguments in Springboot Application
Multiple Scanner Inputs (Java)
How to Return a Custom Object from a Spring Data JPA Group by Query
Deserialization With @Jsonsubtypes for No Value - Missing Property Error
Filenotfoundexception in Src/Main/Resources
Retrieve Integer Values from Excel Using Java
How to Remove All Special Character in a String Except Dot and Comma