I cannot find the reference online (perhaps I read it in a book) but there was an example of some BIOS call that wrote a String to the screen.
The code the wrote the string to the screen checked to make sure that the String wasn't going to go off of the screen and then called a function to write out a char to the screen.
The function that wrote the char to the screen checked to make sure that the character would not be written off of the screen.
Removing the checking code from the function that wrote the character to the screen resulted in a massive speed boost. The was because printing each character happened very often. They also provided a method that did the check for the cases when the screen position was not checked before the call.
So, if you can check at a high level and avoid the checks at the low level you can speed things up significantly.
In the case you provide, if the code is in a loop or if there are a lot of logging statements then there would be a clear benefit since you would:
- remove the string creation (and the associated GC)
- reduce the number of if statements (though hotspote very likely optimizes them out).
I would say that, in general, you should not add anything that is known to be costly if there is an easy work around. This clearly falls into that case - the addition of the if statement is not hard to do, it is a pain to put in later, and it provides a definite speed/memory improvement.
I think the difference between this and premature optimization is that this is known to be always costly,so the issue comes down to is it a cumulative cost you want to add to the program or not? The cost is pretty much constant and it is known at the point of writing the code.