Most usage of string.toLowerCase and string.toUpperCase in our programs has nothing to do with lower or upper casing strings, all what we want to achieve most of the time is case insensitive comparison.
The problem is that toLowerCase will allocate a new string which includes array copy and produce unnecessary garbage for no good reason. The good news is, there is a better and more concise way for achieving this using String.equalsIgnoreCase(String).
Here is a JMH benchmark that shows the difference between using both methods for testing string’s equality.
And the results when I run it on my machine.
Benchmark Mode Cnt Score Error Units StringEqualsBenchmark.withIgnoreCases avgt 10 18.299 ± 0.319 ns/op StringEqualsBenchmark.withLowerCase avgt 10 280.870 ± 14.076 us/op