我需要在循环中设置一个非常大的数组的元素。循环可能continue
在某些情况下,因此必须单独计算数组位置。
我总是需要设置 10个连续的元素。(10 是一个例子。在某些情况下,我可能需要 30 或更多。)
是k+c
(c=0,1,2,... 常数) 还是k++
更好的方法?以下两种解决方案哪个更有效,为什么?
int k = 0;
for (int i = 0; i < aVeryHighNumber; i++) {
if (continueRequired()) {
continue;
}
k = ... // get k as a result of a certain calculation
veryLargeArray[k++] = value0; // these values might be calculated on-the-fly
veryLargeArray[k++] = value1;
veryLargeArray[k++] = value2;
veryLargeArray[k++] = value5;
veryLargeArray[k++] = value4;
veryLargeArray[k++] = value5;
veryLargeArray[k++] = value6;
veryLargeArray[k++] = value4;
veryLargeArray[k++] = value7;
veryLargeArray[k++] = value1;
}
第二种解决方案:
for (int i = 0; i < aVeryHighNumber; i++) {
if (continueRequired()) {
continue;
}
k = ... // get k as a result of a certain calculation
veryLargeArray[k] = value0;
veryLargeArray[k + 1] = value1;
veryLargeArray[k + 2] = value2;
veryLargeArray[k + 3] = value5;
veryLargeArray[k + 4] = value4;
veryLargeArray[k + 5] = value5;
veryLargeArray[k + 6] = value6;
veryLargeArray[k + 7] = value4;
veryLargeArray[k + 8] = value7;
veryLargeArray[k + 9] = value1;
}
理论上,第二个解决方案执行 9 个加法操作(它基本上是一个展开循环),而第一个解决方案执行 9 个递增操作,即它还需要存储 的值k
。但是,现在自增可能是一种非常有效的操作,所以我不确定第二种解决方案是否更快。