Unsafe: efficiently comparing two byte arrays

Paul Sandoz paul.sandoz at oracle.com
Thu Mar 13 12:49:54 UTC 2014

On Mar 13, 2014, at 1:19 PM, Andrew Haley <aph at redhat.com> wrote:
> On 03/13/2014 11:57 AM, Paul Sandoz wrote:
>> Now i am in two minds to whether to add ByteBuffer.compareUnsigned or add Arrays.compareUnsigned.
>> An explosion of methods on Arrays for all types (plus to/from versions) would be annoying.
> Surely it's a no brainer?  All we have to do is add the intrinsics for
> ByteBuffers, then we get fast ByteBuffers and fast array comparisons too.
> I don't see the problem.

For byte[] comparison, I don't think optimal long access is sufficient on it's own due to alignment issues. It would be nice if we can avoid burdening users with alignment issues to ensure the main comparison loop is efficient.

A quick solution is to leverage Unsafe within a ByteBuffer.compareUnsigned method. In fact i believe Unsafe could be used (as Aleksey says in [1]) for put/get as well, which i presume is likely to be much easier/quicker to implement. Might be a good first step until a more superior intrinsics solution is implemented?


[1] https://bugs.openjdk.java.net/browse/JDK-8026049

More information about the core-libs-dev mailing list