你在谈论一个非常微不足道的开销。我有一个小程序可以帮助您了解它的重要性:
class Bar {
void foo(double d) {
double y = (d + 1) * d / 7.1 % 31.3 + 13.12 * 20.002;
}
void foo1(double[] args) {
for (double d : args) {
foo(d);
}
}
void foo2(double[] args) {
for (double d : args) {
double y = (d + 1) * d / 7.1 % 31.3 + 13.12 * 20.002;
}
}
}
这是一个测试和样品运行
public class Main {
public static void test(int n) {
System.out.print(n + ",");
double is[] = new double[n];
for (int i = 0; i < is.length; i++) {
is[i] = i * 1.3;
}
Bar bar = new Bar();
long span;
long start = System.currentTimeMillis();
bar.foo1(is);
span = System.currentTimeMillis() - start;
System.out.print(span + ",");
start = System.currentTimeMillis();
bar.foo2(is);
span = System.currentTimeMillis() - start;
System.out.print(span + "\n");
}
public static void main(String[] args) {
test(10000000);
test(20000000);
test(30000000);
test(40000000);
test(50000000);
test(60000000);
}
}
这是一个输出:
10000000,389,383
20000000,743,766
30000000,1130,1113
40000000,1497,1474
50000000,1866,1853
60000000,2243,2239
foo 方法越复杂,差异就越小。所以恕我直言,忘记性能,考虑可维护性。