I have funcion, which is called very frequently. This function has two nested for loops inside. Each of the for loops iterates from 0 to 900. The code looks like this:
for (int j = 0; j < width; j++)
{
for (int k = 0; k < height; k++)
{
switch (Dim2[j * width + k])
{
case 0:
cwA = Dim0[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
ccwA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
oppA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
cwB = Dim3[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
ccwB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
oppB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
break;
case 1:
cwA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
ccwA = Dim0[j * width + ((k == 0) ? (height - 1) : (k - 1))];
oppA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
cwB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
ccwB = Dim3[j * width + ((k == 0) ? (height - 1) : (k - 1))];
oppB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
break;
case 2:
cwA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + k];
ccwA = Dim0[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
oppA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
cwB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + k];
ccwB = Dim3[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
oppB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
break;
case 3:
cwA = Dim0[j * width + ((k == 0) ? (height - 1) : (k - 1))];
ccwA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + k];
oppA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
cwB = Dim3[j * width + ((k == 0) ? (height - 1) : (k - 1))];
ccwB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + k];
oppB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
break;
}
woll = (((oppB + ccwB) + cwB) + Dim3[j * width + k]) > 0;
collision = ((Dim0[j * width + k] == oppA) && (cwA == ccwA)) && (Dim0[j * width + k] != cwA);
Dim6[j * width + k] = (short)(3 - Dim2[j * width + k]);
if (woll || collision)
{
Dim4[j * width + k] = Dim0[j * width + k];
}
else
{
Dim4[j * width + k] = _phase ? cwA : ccwA;
}
}
}
it takes around 0.1 second to execute these for loops, which is too slow. I've replaced two-dimentional arrays with 1 dimentional, this significantly improved performance. Are there any other performance improvements for the code? Will it work faster if I migrate it to c++? Should I use any other language for arrays manipulation? What would you suggest?
Thanks in advance,
Sam