Unsafe: efficiently comparing two byte arrays

Paul Sandoz paul.sandoz at oracle.com
Thu Mar 13 11:57:26 UTC 2014


On Feb 28, 2014, at 11:29 PM, Martin Buchholz <martinrb at google.com> wrote:

> Are word-size reads in ByteBuffer actually intrinsified?  I could find no evidence for that.  Perhaps this is an important missing optimization for hotspot to make?
> 
> I see DirectByteBuffer, but not garden-variety ByteBuffer, using Unsafe.
> share/classes/java/nio/Direct-X-Buffer.java.template
> 

Yes, no choice :-) I see it only does it when unaligned access is supported:

    private long getLong(long a) {
        if (unaligned) {
            long x = unsafe.getLong(a);
            return (nativeByteOrder ? x : Bits.swap(x));
        }
        return Bits.getLong(a, bigEndian);
    }

I suppose it could detect if the address + position also aligns, but ideally that should be hoisted out of any loop so the unaligned pre/post bytes are handled separately to the aligned sequence viewed as longs, which most likely means explicit code for the comparison use-case.

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.

Paul.



More information about the core-libs-dev mailing list