Reputation: 233
Which of the 2 is better from a processing or optimizing point of view?
I feel Option 1 is more readable, but I've been told Option 2 is more efficient. Is that so?
if (value != null) {
if (value.equalsIgnoreCase(ApplicationConstants.A)) {
} else if (value.equalsIgnoreCase(ApplicationConstants.B)) {
}
}
Option 2:
if ((value != null) && (value.equalsIgnoreCase(ApplicationConstants.A))) {
} else if ((value != null) && (value.equalsIgnoreCase(ApplicationConstants.B))) {
}
Upvotes: 0
Views: 131
Reputation: 44821
There's nothing here to care about performance wise, write your code so it's as readable as you can make it.
When performance testing later highlights areas that need to be optimized then and only then optimize only the places that need it.
To make it more readable you can invert your tests to get rid of the null check:
if (ApplicationConstants.A.equalsIgnoreCase(value)) {
} else if (ApplicationConstants.B.equalsIgnoreCase(value)) {
}
Upvotes: 8
Reputation: 3436
The first option is better as with one condition check you can decide. so if value != null then only it will enter else it will not even enter the conditional block. But in 2nd option it will check if condition , and if false also it wd check else condition (for value == null).
Upvotes: 0
Reputation: 5554
I would go with option 1 as in option 2, more no of comparisons are made.
Upvotes: 0
Reputation: 63698
Option 1
is efficient since there is no redundant null
check.
Upvotes: 2
Reputation: 7924
I'd expect the first to be slightly more efficient, because &&
is short-circuit, so it gives multiple conditional branches anyway. But if you want to be certain, time them.
Upvotes: 0