以转小写为例
方法一
public static String firstToLowerCase1(String s){
if(Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
方法二
public static String firstToLowerCase2(String s){
Character c = s.charAt(0);
if (Character.isLowerCase(c)){
return s;
}else {
char[] chars = s.toCharArray();
chars[0] = Character.toLowerCase(c);
return String.valueOf(chars);
}
}
对比
public class Main {
public static void main(String[] args) {
/**
* 各运行10000000次
*/
long time1 = getTaskRunTime(() -> {
for (int i = 0; i < 10000000; i++) {
firstToLowerCase1("AbCCC");
}
});
long time2 = getTaskRunTime(() -> {
for (int i = 0; i < 10000000; i++) {
firstToLowerCase2("AbCCC");
}
});
System.out.println("time1:" + time1); // time1:434
System.out.println("time2:" + time2); // time2:190
}
private static long getTaskRunTime(Runnable runnable){
long start = System.currentTimeMillis();
runnable.run();
return System.currentTimeMillis() - start;
}
}