What is the most efficient way to make the first character of a String
lower case?
I can think of a number of ways to do this:
Using charAt()
with substring()
String input = "SomeInputString";
String output = Character.toLowerCase(input.charAt(0)) +
(input.length() > 1 ? input.substring(1) : "");
Or using a char
array
String input = "SomeInputString";
char c[] = input.toCharArray();
c[0] = Character.toLowerCase(c[0]);
String output = new String(c);
I am sure there are many other great ways to achieve this. What do you recommend?
Best Answer
I tested the promising approaches using JMH. Full benchmark code.
Assumption during the tests (to avoid checking the corner cases every time): the input String length is always greater than 1.
Results
The score are operations per second, the more the better.
Tests
test1
was first Andy's and Hllink's approach:test2
was second Andy's approach. It is alsoIntrospector.decapitalize()
suggested by Daniel, but without twoif
statements. Firstif
was removed because of the testing assumption. The second one was removed, because it was violating correctness (i.e. input"HI"
would return"HI"
). This was almost the fastest.test3
was a modification oftest2
, but instead ofCharacter.toLowerCase()
, I was adding 32, which works correctly if and only if the string is in ASCII. This was the fastest.c[0] |= ' '
from Mike's comment gave the same performance.test4
usedStringBuilder
.test5
used twosubstring()
calls.test6
uses reflection to changechar value[]
directly in String. This was the slowest.Conclusions
If the String length is always greater than 0, use
test2
.If not, we have to check the corner cases:
If you are sure that your text will be always in ASCII and you are looking for extreme performance because you found this code in the bottleneck, use
test3
.