我在这里有两个不同的递归函数,用于在 Java 中反转字符串:
Long ms1 = System.currentTimeMillis();
String str1 = reverse1(str);
ms1 = System.currentTimeMillis() - ms1;
Long ms2 = System.currentTimeMillis();
String str2 = reverse2(str);
ms2 = System.currentTimeMillis() - ms2;
System.out.println("Input: " + str);
System.out.println(" Length: " + str.length());
System.out.println("Reverse 1:");
System.out.println(" " + herp + " function calls");
System.out.println(" " + ms1 + " milliseconds");
System.out.println("Reverse 2:");
System.out.println(" " + derp + " function calls");
System.out.println(" " + ms2 + " milliseconds");
}
public static String reverse1(String str){
herp++;
if(str.length() == 1) return str;
return reverse1(str.substring(str.length()/2)) + reverse1(str.substring(0, str.length()/2));
}
public static String reverse2(String str){
derp++;
if(str.length() == 1) return str;
return reverse2(str.substring(1)) + str.charAt(0);
}
给定一个长度为 5000 的字符串,这是程序的输出:
Input: ...
Length: 5000
Reverse 1:
9999 function calls
16 milliseconds
Reverse 2:
5000 function calls
52 milliseconds
现在为什么函数调用两倍的函数要快 3 倍?我应该如何构建我的递归函数以在 Java 中实现最大速度?