【发布时间】:2018-12-14 22:34:53
【问题描述】:
我想优化这个程序。目前我的程序运行缓慢,因为程序中的函数非常依赖于程序中的其他函数。对此进行优化的最佳方法是什么?
public class MyClass {
public static void main(String args[]) {
int[] testValues = {3, 5, 10};
for (int i = 0; i < testValues.length; ++i) {
System.out.println(first(testValues[i]));
}
}
public static int first(int a) {
int b;
if (a <= 1) {
if (a == 1) {
b = convertOne(a);
} else {
b = convertTwo(a - 1);
}
} else {
return next(a);
}
return b;
}
public static int convertOne(int c) {
return++c;
}
public static int convertTwo(int d) {
int i = 1;
for (i = d * 11; i > d; i--) {
i--;
}
return i;
}
public static int next(int e) {
int container = first(e - 1);
return container + first(e - 2);
}
}
【问题讨论】:
-
需要转换为循环的递归部分在哪里?我没有看到。
-
@MangoLato
firstcallnext,nextcallfirst. -
下一次调用时,它花费的时间比正常情况要长。所以在 next() 中调用 first() 部分需要迭代。我认为那将是首先执行。
-
你的预期输出是什么?
-
首先,递归严格来说是一个调用自身并且有退出条件的函数。递归本身不是一个非常推荐的方法,因为它很慢并且可以结束引发堆栈溢出异常。话虽这么说,你有一个循环调用。考虑重构你的代码。
标签: java optimization