Skip to content

Instantly share code, notes, and snippets.

@AdamStelmaszczyk
Last active December 19, 2015 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamStelmaszczyk/5593723da543940acfd1 to your computer and use it in GitHub Desktop.
Save AdamStelmaszczyk/5593723da543940acfd1 to your computer and use it in GitHub Desktop.
Most efficient way to make the first character of a String lower case?
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.infra.Blackhole;
import java.lang.reflect.Field;
public class MyBenchmark {
@Benchmark
public void test1(Blackhole blackhole) {
String string = "SomeInputString";
string = Character.toLowerCase(string.charAt(0)) + string.substring(1);
blackhole.consume(string);
}
@Benchmark
public void test2(Blackhole blackhole) {
String string = "SomeInputString";
char c[] = string.toCharArray();
c[0] = Character.toLowerCase(c[0]);
string = new String(c);
blackhole.consume(string);
}
@Benchmark
public void test3(Blackhole blackhole) {
String string = "SomeInputString";
char c[] = string.toCharArray();
c[0] += 32;
string = new String(c);
blackhole.consume(string);
}
@Benchmark
public void test4(Blackhole blackhole) {
String string = "SomeInputString";
StringBuilder sb = new StringBuilder(string);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
string = sb.toString();
blackhole.consume(string);
}
@Benchmark
public void test5(Blackhole blackhole) {
String string = "SomeInputString";
string = string.substring(0, 1).toLowerCase() + string.substring(1);
blackhole.consume(string);
}
@Benchmark
public void test6(Blackhole blackhole) {
String string = "SomeInputString";
try {
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[]) field.get(string);
value[0] = Character.toLowerCase(value[0]);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
blackhole.consume(string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment