请考虑以下代码:
int max = 1000;
int min = 0;
// Code sample A
for(int i = 0; i < array.Length; i++)
{
if (array[i] < min) min = array[i];
else if (array[i] > max) max = array[i];
}
和
// Code Sample B
for (int i = 0; i < array.Length; i++)
{
if (array[i] < min) min = array[i];
}
for (int i = 0; i < array.Length; i++)
{
if (array[i] > max) max = array[i];
}
以上两个代码示例中哪一个更有效?
我知道有些人会说第一个代码示例会更快,因为它会在一次迭代中执行两个指令。而第二个是在两个单独的for循环中完成的。我不太确定这是否属实。请解释一下。
答案 0 :(得分:1)
为了简单起见,
,例如A,
i
一次。 i
分配给array.Length
次。i
次增加array.Length
次值。array.Length
次。如果是B,
i
两次。i
2 * array.Length
次。i
值提高2 * array.Length
次。array.Length
次。那么,您更喜欢哪一个?
答案 1 :(得分:0)
Prajwal的答案非常准确。 测试它(在Java中)并不困难:
public static void main(String[] args) {
int max = 1000;
int min = 0;
long start, stop, diff;
int[] arr = new int[100_000];
for (int i = 0; i < arr.length; i++)
arr[i] = (int) (-500_000 + Math.random() * 1_000_000);
start = System.nanoTime();
// Code sample A
for(int i = 0; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
else if (arr[i] > max)
max = arr[i];
}
stop = System.nanoTime();
diff = stop - start;
System.out.println("nanoseconds needed for A: " + diff);
min = 0; max = 1000;
start = System.nanoTime();
// Code Sample B
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
stop = System.nanoTime();
diff = stop - start;
System.out.println("nanoseconds needed for B: " + diff);
}
结果:
nanoseconds needed for A: 563581
nanoseconds needed for B: 1018710