Signed division by 2 and right shift by 1 are not completely equivalent. Division by 2 rounds towards zero, even for negative numbers. Right shift by 1 rounds downwards, which means -1 >> 1
is -1
(whereas -1 / 2
is zero).
Concretely, that means that if the JIT compiler can not (or does not) prove that a number can not be negative (if you had posted the full code, I might have been able to check that), it has to do a something more complicated than merely a right shift - something like this: (divides eax
by 2 and clobbers edi
, based on what GCC output)
mov edi, eax
shr eax, 31
add eax, edi
sar eax, 1
If you had used a right shift by 1, it would just be something like
sar eax, 1
It's not a big difference, but it is a difference, so the "it doesn't make any difference"-crowd can go home now. Ok it's only on the loop initialization, so it doesn't have a serious impact on performance, but let's not forget that this is library code - different guidelines apply. Specifically, readability is less emphasized, and the guideline "don't waste performance unless you absolutely must" is more emphasized. Under the circumstances, there is no good reason to write size / 2
there, all that would do is make the performance a tiny bit worse. There is no upside.
Also, I find this readability thing a little silly in this case. If someone really doesn't know what size >> 1
does, that's their problem - it's just one of the basic operators, not even some convoluted combination of operators, if you can't read it then you don't know Java.
But feel free to use size / 2
in your own code. The takeaway from this answer shouldn't be "division by 2 is bad", but rather, "library code shouldn't sacrifice performance for readability".