I have the following java function, to count common elements in two sorted arrays. Note the line with the question mark.
public static int overlap(int[] a, int[] b)
{
int i = 0, j = 0;
int res = 0;
while(i < a.length && j < b.length)
{
if(a[i] > b[j])
j ++;
else if(a[i] < b[j])
i ++;
else if(a[i] == b[j]) // ?
{
res ++;
i ++;
j ++;
}
}
return res;
}
Clearly, that last if-statement doesn't need to be there: at that point we know that the two values are equal. However, when I test the speed (I was checking whether the order of the checks made any difference), the method with the superfluous check is invariably faster than the one without (sometimes by a factor of two).
What is going on here? Some mysterious optimization? Am I overlooking something obvious? I'm using the stand compiler, version 1.8. I can't read bytecode, so I don't know what's going on under the hood.
Here is a full test class: https://gist.github.com/pbloem/1523283211454ec58ce9c5b45204eebd
Bytecode: https://gist.github.com/pbloem/ce4f6758f0bb1424c155c26e83ca88a1