Why JNI call to native method is slower than simil

2019-03-13 17:51发布

问题:

I'm developing JNI implementation similar to sun.misc.Unsafe but with extended memory management.

How to explain that call time of native methods from sun.misc.Unsafe and from my developed library is extremely different?

Some numbers: sun.misc.Unsafe.getInt(address) takes ~1ns when my similar method takes ~10ns

Both implementations are quite the same, following source code of openJDK, just return variable by pointer. Unsafe in JNI module, registered in the same manner as other.

How to speed up JNI call? What makes Unsafe so special for performance?

Thanks, Yury/

回答1:

If you look for the source of the native methods in the Unsafe class you will find there is not JNI implementations. Instead, Unsafe methods are inlined as machine code. getInt(long) for example becomes one machine code instruction.

For this reason, you can't write a JNI method which is as fast as using Unsafe, without change the JVM so it inlines the machine code.