A DESCRIPTION OF THE REQUEST :
The implementation of hashCode() in java.lang.String uses a local variable val to store the value instance field reference, presumably to avoid the cost of a GETFIELD operation in the loop (is there another reason?)
However, the loop condition checks value.length which itself adds a GETFIELD and ARRAYLENGTH operation per iteration of the loop.
To be consistent with the existing optimization, the loop should reference val.length instead of value.length, or it can further cache val.length in a local variable.
Another alternative is to use a while loop such as the one in String.equals() with a decreasing counter compared to zero if it is more efficient (if not, then equals should be changed to a regular for loop instead - again, consistency is desired).
Finally, the caching of val.length can optionally be done in-line in the if condition above in order to save one extra field access, i.e. if (h == 0 && (length = value.length) > 0) - while generally considered less aesthetic, if it has any performance gains then String.hashcode is certainly a good candidate for accepting this tradeoff.
JUSTIFICATION :
Either remove the cached field optimization if it has no benefit, or update all usages to use it - there's no point in doing half the optimization.
The implementation of hashCode() in java.lang.String uses a local variable val to store the value instance field reference, presumably to avoid the cost of a GETFIELD operation in the loop (is there another reason?)
However, the loop condition checks value.length which itself adds a GETFIELD and ARRAYLENGTH operation per iteration of the loop.
To be consistent with the existing optimization, the loop should reference val.length instead of value.length, or it can further cache val.length in a local variable.
Another alternative is to use a while loop such as the one in String.equals() with a decreasing counter compared to zero if it is more efficient (if not, then equals should be changed to a regular for loop instead - again, consistency is desired).
Finally, the caching of val.length can optionally be done in-line in the if condition above in order to save one extra field access, i.e. if (h == 0 && (length = value.length) > 0) - while generally considered less aesthetic, if it has any performance gains then String.hashcode is certainly a good candidate for accepting this tradeoff.
JUSTIFICATION :
Either remove the cached field optimization if it has no benefit, or update all usages to use it - there's no point in doing half the optimization.
- duplicates
-
JDK-8058643 (str) Improve String.hashCode implementation
-
- Resolved
-