简体   繁体   中英

java - Loop optimization on int array

I would like to know, which is fast way to write/read in an int array.

Here my Java code: I have three int arrays, two in read access and one int array in write access.

for(int j = h20 ; j < h21 ; j++){
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[j*h31 + i] )  continue; //condition 
        arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];      
    }   
}

My code is a classic 2D array loop, there are just one special condition to check.

Is it other way to write this code to decrease processing time?

Thx.

You can reduce the amount of calculations, if you separate them by variables. In your case, any calculation that relies on j alone doesn't have to be inside the inner loop because the result won't change for the rest of the loop. Instead, calculate the values outside and only use the result in the inner loop.

for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = (j+decY)*w11 + decX;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition 
        arr1[tmp2 + i] = arr2[tmp3 + i];      
    }   
}

Edit: If you want to reduce this even more, you could rewrite the calculation for tmp2 :

(j+decY)*w11 + decX ==> j*w11 + decY*w11 + decX

Then, you could extract the decY*w11 + decX into its own variable outside the first loop.

int tmp0 = decY*w11 + decX;
for(int j = h20 ; j < h21 ; j++){
    int tmp1 = j*h31;
    int tmp2 = j*w11 + tmp0;
    int tmp3 = j*w21;

    // j won't change inside here, so you can simply use the precalculated values
    for(int i = w20 ; i < w21 ; i++){
        if( int_color == arr3[tmp1 + i] )  continue; //condition 
        arr1[tmp2 + i] = arr2[tmp3 + i];      
    }   
}

But this will save you only one addition per iteration, so I don't think it's worth the extra effort.

Removing calculations, especially multiplications might help.

For arr3 this would be:

final int icolor = int_color;
final int ix3 = h20 + w20;
final int dx3 = h31 + h21 - h20;

for (int j = h20; j < h21; ++j) {
    for (int i = w20 ; i < w21 ; ++i) {
        assert ix3 == j*h31 + i;
        if (icolor != arr3[ix3]) {
            arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
        }
        ++ix3;
    }
    ix3 += dx3;
}

Whether this is really worthwile one needs to test.

Depending on the frequency of the condition, one might think of using System.arraycopy for consecutive ranges of i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM