I’m looking to improve performance of JNI calls. I’ve written a couple of JNI libraries in the past and I always wondered why the performance is so bad compared to the actual performance of the algorithm in C.
According to my experience, native code usually runs about ten to fifty times faster than the same code in Java, given a reasonable complex algorithm. When adding JNI method calls to use the native code from Java, performance gets extremely worse and you loose the advantage of a native library.
On the other hand, native methods provided by the JVM have significantly better performance. I do not remember the actual numbers, but when you compare some of the native methods in sun.misc.Unsafe with native methods of the same functionality provided in a JNI library, you can measure a significant difference in method call performance.
So, the JVM somehow gets better performance on its own statically linked native methods.
Should I consider using statically linked libraries (yes it’s possible, see below)? Does anybody have experience with that?
Common pitfalls using JNI
There is a good article on Best practices for using the Java Native Interface, which mentions important points to look at.
Statically linked JNI libraries
There are basically two ways to statically link your own library with the JVM:
- Implement a JVM launcher, which includes your native code and use the invocation API to instantiate the JVM. So you basically write your own “java” command binary.
- Get the code of the Java VM and statically link it with your library. Again, you build your own “java” command binary.
See also Section “Static linking” in this IBM article.