I don't know what are you trying to do and, as you said, the difference in time will be minor i.e. undetectable. , but the answer is simple: only changing the value will probably be "faster" and, as said by cowls, easier to read, so you should go for:
for (Foo foo : fooList) {
foo.setBar(false);
}
Explaining a little bit:
I'm assuming you want to calculate future efficiency in other programs so I would recommend you calculate best, worst and average case. In this case you could calculate how much time each statement will take if you have to change all the booleans or just a few.
For example, you could say foo.setBar(false)
takes A
time and the if (foo.isBar())
will take B
time.
Lets say you have only 3 foos
in the foolist
you can experience the following:
- Worst case: you have to change
bar
in all 3 foos
.
- Average: sometimes 1 or 2 at most bars need to be changed.
- Best case: no bars need to be changed.
Doing only A
you will have for all 3 cases total time execution of 3A
. If you do it with the if
, it will take:
- Worst case: 3A + 3B
- Average: (1-2)A + 3B
- Best case: 3B
If we assume B < A
then the if option will only be faster in third case. If B<<A
then the average will be better. But the worst case will be always worse than doing just the assignment. And in this case, probably A and B will be similar or equal so you will have (A=B):
- Worst case: 6A
- Average case: (4-5) A
- Best case: 3A
So, the first option (shown at the beginning) will be the best.
This will be useful for any other language or performance issue you face. Although if you want you could review official Java docs to check whether there are special VM improvements for this.