I need the set the elements of a very large array in a loop. The loop may continue in certain cases, so the array position must be counted separately.
I always need to set 10 consecutive elements. (10 is an example. In some scenarios, I might need 30 or more.)
Is k+c (c=0,1,2,… constant) or k++ a better approach? Which is more efficient from the two solutions below, and why?
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;
}
The second solution:
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;
}
In theory, the second solution performs 9 add operations (it’s basically an unrolled loop), while the first one does 9 incrementing, i.e. it needs to store the value of k as well. However, self-incrementing by one is probably a very efficient operation nowadays, so I’m not sure if the second solution is faster or not.
As far as the compiled code is represented it is simply binary additions.
The
++code is simply short hand for+1. When these are converted to binary additions after compiling there is no difference between the two.Even if there does happen to be a difference any modern computer would show no difference in computation times until you do this 1000’s of times.