Is get/put from a non-direct bytebuffer faster than get/put from direct bytebuffer ?
If I have to read / write from direct bytebuffer , is it better to first read /write in to a thread local byte array and then update ( for writes ) the direct bytebuffer fully with the byte array ?
If you are comparing heap buffer with direct buffer which does not use native byte order (most systems are little endian and the default for direct ByteBuffer is big endian), the performance is very similar.
If you use native ordered byte buffers the performance can be significantly better for multi-byte values. For
byteit makes little difference no matter what you do.In HotSpot/OpenJDK, ByteBuffer uses the Unsafe class and many of the
nativemethods are treated as intrinsics. This is JVM dependent and AFAIK the Android VM treats it as an intrinsic in recent versions.If you dump the assembly generated you can see the intrinsics in Unsafe are turned in one machine code instruction. i.e. they don’t have the overhead of a JNI call.
In fact if you are into micro-tuning you may find that most of the time of a ByteBuffer getXxxx or setXxxx is spend in the bounds checking, not the actual memory access. For this reason I still use Unsafe directly when I have to for maximum performance (Note: this is discouraged by Oracle)
I would hate to see what that is better than. 😉 It sounds very complicated.
Often the simplest solutions are better and faster.
You can test this yourself with this code.
prints
I am pretty sure a JNI call takes longer than 1.2 ns.
To demonstrate that its not the “JNI” call but the guff around it which causes the delay. You can write the same loop using Unsafe directly.
prints
So you can see that the
nativecall is much faster than you might expect for a JNI call. The main reason for this delay could be the L2 cache speed. 😉All run on an i3 3.3 GHz