I have a list I need to process. The items are either enabled or disabled. The user can choose whether or not to show disabled items.
So you have cond2 that depends on the items, and cond1 that does not. Here’s the dilemma I got into: Should I use cond1 && !cond2 or !(!cond1 || cond2)? Or should I check for the cond2 (show disabled items) before the loop? I also thought (as you will see in the code I put) if I should put the cond2 before cond1, because cond2
is a boolean variable, and with “short-circuits” (lazy evaluation?), it will be faster?
My main concern was speed. If I have many items in the loop, this might be an important change.
This is code that illustrates the options:
// First Option
for (String item : items) {
doSomethingFirst(item);
if (isDisabled(item) && !showDisabled) {
continue;
}
doSomethingElse(item);
}
// Second Option
for (String item : items) {
doSomethingFirst(item);
if (!(!isDisabled(item) || showDisabled)) {
continue;
}
doSomethingElse(item);
}
// Third Option
if (showDisabled) {
for (String item : items) {
doSomethingFirst(item);
doSomethingElse(item);
}
} else {
for (String item : items) {
doSomethingFirst(item);
if (isDisabled(item)) {
continue;
}
doSomethingElse(item);
}
}
So, does the order of isDisabled(item) and showDisabled matter? Should I be checking on things before the loop? Or does the compiler optimize that? (I doubt…)
PS I don’t know how I would take measurements to see actual values, if it’s relevant please do.
Thanks.
In Java the expression is evaluated from left to right. With
&&if the first condition is false, the second one is not executed, with||if the first condition is true, the second one is not executed.So try to put the condition that can be resolve faster in first place, in your case
showDisabled.For the third example, it looks better because you check the boolean only once but I guess it don’t really change performance, a bool comparison is not really costly. You will probably have better improvement to do in other part of your code. (and for the readable aspect it’s not my favorite – quite long)
If you want to measure the performance in your case use a profiler for example.
Or add in your code :
You’ll have to put your code in a loop, to make it relevant. And you will probably notice that Java will increase the performance after some loops ;).