Skip to content

Instantly share code, notes, and snippets.

@micahjsmith
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save micahjsmith/c7c9d31b342c115aef90 to your computer and use it in GitHub Desktop.

Select an option

Save micahjsmith/c7c9d31b342c115aef90 to your computer and use it in GitHub Desktop.
Test various Java methods for extracting the first letter of a string, see http://stackoverflow.com/q/18201191/2514228
public class TestFirstLetterMethods{
public static final int N_SIM = 1000;
public static void main(String[] args){
long method1 = 0;
long method2 = 0;
long method3 = 0;
for (int i=0; i<N_SIM; i++){
String example = "something";
String firstLetter = "";
long l1=System.nanoTime();
firstLetter = String.valueOf(example.charAt(0));
method1 += System.nanoTime()-l1;
long l2=System.nanoTime();
firstLetter = example.substring(0, 1);
method2 += System.nanoTime()-l2;
long l3=System.nanoTime();
firstLetter = Character.toString(example.charAt(0));
method3 += System.nanoTime()-l3;
}
System.out.println("String.valueOf average: "+method1/N_SIM);
System.out.println("example.substring average: "+method2/N_SIM);
System.out.println("Character.toString average: "+method3/N_SIM);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment