Consider the following two ways of writing a loop in Java to see if a list contains a given value:
Style 1
boolean found = false;
for(int i = 0; i < list.length && !found; i++)
{
if(list[i] == testVal)
found = true;
}
Style 2
boolean found = false;
for(int i = 0; i < list.length && !found; i++)
{
found = (list[i] == testVal);
}
The two are equivalent, but I always use style 1 because 1) I find it more readable, and 2) I am assuming that reassigning found
to false
hundreds of times feels like it would take more time. I am wondering: is this second assumption true?
Nitpicker's corner
- I am well aware that this is a case of premature optimization. That doesn't mean that it isn't something that is useful to know.
- I don't care which style you think is more readable. I am only interested in whether one has a performance penalty compared to the other.
- I know that style 1 has the advantage of allowing you to also put a
break;
statement in theif
block, but I don't care. Again, this question is about performance, not style.