When ever we do String comparisons. There's always a question arises, shall we use String.toUpper/LowerCase
function before comparing the Strings or equalsIgnoreCase is better.
Well the answer is both are same and gives the same performance. In fact equalsIgnoreCase function uses toLowerCase function internally. You can check this in String.java code.
It depends on the situation which function you should use. If you know one of the input is static and always going to be lowercase/uppercase. You can just convert one of the String to the same case and then compare it.
function before comparing the Strings or equalsIgnoreCase is better.
Well the answer is both are same and gives the same performance. In fact equalsIgnoreCase function uses toLowerCase function internally. You can check this in String.java code.
It depends on the situation which function you should use. If you know one of the input is static and always going to be lowercase/uppercase. You can just convert one of the String to the same case and then compare it.
As you don't specifically state it, although your point about efficiency implies it:
ReplyDeleteIf you want to compare one string against 2 strings in an if/else-if, it is more efficient to call .toUpperCase() (or lower) on the String, then compare it against the other two using .equals() to avoid repeated calls to it using equalsIgnoreCase().
Came across this due to a similar issue. Actually, a Borland performance tuning document states it does make a difference. (probably slight) But Anon is correct if you will re-use one of the strings.
ReplyDelete"Finally, the method java.lang.String.equalsIgnoreCase() is more efficient than the combination of the toLowerCase() and equals(). If you look at the source code of the java.lang.String class (the source code of the JDK is available as a src.jar file under your JDK directory), you will see that equalsIgnoreCase() parses the String only once and does not use a temporary object. toLowerCase() parses the String once and creates a new String (which is then returned) equalsTo() then parses the String again."