Options 1:
boolean isFirst = true;
for (CardType cardType : cardTypes) {
if (!isFirst) {
descriptionBuilder.append(" or ");
} else {
isFirst = false;
}
//other code not relevant to this theoretical question
}
Option 2:
boolean isFirst = true;
for (CardType cardType : cardTypes) {
if (!isFirst) {
descriptionBuilder.append(" or ");
}
isFirst = false;
//other code not relevant to this theoretical question
}
My analysis: Both code has same semantic.
1st code) I'm not sure if this code has two branches (in terms of branch predictor) or one branch. I was looking into http://en.wikipedia.org/wiki/X86_instruction_listings but couldn't figure out that there is a X86 instruction something like "if previous condition value was false jump there", to avoid two branch predictions (very bad)
2nd code) most likely to always perform simple MOV (to register or element most likely already in the cache), which is relatively inexpensive (few cycles at most)
So, my opinion is that unless processor decode into microcode instructions can do something smart or X86 instruction exist to avoid necessary branch predictions, 2nd code is faster.
I understand that this is purely theoretical question, since in practice, this branch can make an application 0.000000002% faster or something like that.
Did I miss something?
EDIT: I added a loop for giving more "weight" to branch in question
EDIT2: The question is about Intel architecture for branch prediction (Pentium and newer processors).