use of Unsafe for ASCII detection

Andrew Haley aph at
Thu Jan 7 11:54:03 UTC 2016

On 07/01/16 10:04, Andrew Haley wrote:
> If you allocate a temp ByteBuffer object carefully so that it does not
> escape, it will be removed and you should get the same code as
> directly using Unsafe.  I certainly tested it during the work on
> Unsafe.getXXUnaligned and it was the same.  I'll have a look at your
> example.

I tried your test.

The ByteBuffer allocation is not being removed because it's not inlined:

   @ 1   java.nio.ByteBuffer::wrap (8 bytes)
      @ 4   java.nio.ByteBuffer::wrap (20 bytes)
        @ 7   java.nio.HeapByteBuffer::<init> (14 bytes)
          @ 10   java.nio.ByteBuffer::<init> (45 bytes)   callee is too large

Oops: we're really missing a trick.  So, I'll try to increase the
inline limit so that it's big enough to inline everything: I set it to
100 with -XX:MaxInlineSize=100 .

The other thing is that you're doing a lot of byte-reversing because
ByteBuffer.getLong() is always big-endian.  Do this:

   ByteBuffer b = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());

I get:

Unsafe stride 8: 0.22454525012941629
Buffer stride 8: 0.22788670497576385
Buffer stride 1: 1.0007217052423052

Yippee!  :-)

There are some lessons to be learned here.  We really should try to
inline ByteBuffer constructors to give escape analysis a chance.  And
if you want buffers in native byte order you have to ask for them.

And finally, wrapped ByteBuffers can be a perfectly good substitute for
Unsafe access to byte arrays.


More information about the core-libs-dev mailing list