dhilst

JNI tunning lookups by caching

Doing class, method and field lookups can slow down the execution time of your native methods. Is a common pratice in JNI to cache the used classes, methods and fields IDs. Since the look ups are needed in execution time, doing it only once may improve execution time.

Method and fields IDs are easy to cache. You simply do the lookup and save the result to some static variable. But classes and objects are different. They hold references and references are not valid forever, they may garbage collected. To pin the references you need to create global references by using NewGlobalRef, and this one need to be reverted by DeleteGlobalRef when the reference is not needed anymore.

To have sure that cache is initialized when the first native method is called is a common pratice to initialize cache on JNI_OnLoad function. This function is called when the native library is loaded. Adding the call to System.loadLibrary to a static block makes the library be loaded and cache populated as soon as the class is loaded. This makes accessing cache from native methods calls simpler and safer.

The following gists snippets show how to use classes, methods and fields ID caching with JNI.

Cheers, :+1: