StringCoding.hasNegatives

Brett Okken brett.okken.os at gmail.com
Fri Oct 1 12:57:48 UTC 2021


I know java.lang.StringCoding.hasNegatives has a
HotSpotIntrinsicCandidate annotation/implementation, but is there
interest/value in a faster pure java implementation?

Using Unsafe to read and compare 8 bytes at a time as a long is faster
than the current simple implementation both in interpreter only mode
and default hotspot compiler mode. I can provide jmh bencmark and
results if this is worthwhile to pursue.

Thanks,

Brett

    private static final long NEGATIVE_MASK = 0x8080808080808080L;

    public static boolean hasNegatives(byte[] ba, int off, int len) {
        int i = off;
        final int endIdx = off + len;

        // align to 8 byte reads
        while ((i & 7) != 0 && i < endIdx) {
            if (ba[i++] < 0) {
                return true;
            }
        }

        // read 8 bytes at a time as a long (platform endian-ness does
not matter)
        // to check if any have negative bit set
        final Unsafe unsafe = Unsafe.getUnsafe();
        for (int j = endIdx - 7; i < j; i += 8) {
            final long val = unsafe.getLong(ba,
Unsafe.ARRAY_BYTE_BASE_OFFSET + i);
            if ((val & NEGATIVE_MASK) != 0) {
                return true;
            }
        }

        // process trailing bytes 1 by 1
        for ( ; i < endIdx; i++) {
            if (ba[i] < 0) {
                return true;
            }
        }

        return false;
    }


More information about the core-libs-dev mailing list