Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to enhance reflection performance with jni?

On my code I do a lot of reflection lookups, so I was trying to improve it somehow.

This is a sample of my jni setter method:

JNIEXPORT jobject JNICALL 
Java_org_orman_mapper_Model_fieldSetFloat(JNIEnv * env, jobject  obj, jobject model, jstring field_name, jstring field_type, jfloat value, jclass clazz)
{
    const char* utf_string_name = (*env)->GetStringUTFChars (env, field_name, 0);
    const char* utf_string_type = (*env)->GetStringUTFChars (env, field_type, 0);

    jfieldID id = (*env)->GetFieldID(env, clazz, utf_string_name, utf_string_type);
    (*env)->SetFloatField(env, model, id, value);
    return model;
}

The intrisics of calls like SetFloatField, does it skip any java security checks?

I haven't noticed any gain on performance.

like image 831
kaneda Avatar asked Dec 19 '25 03:12

kaneda


1 Answers

Is it possible to enhance reflection performance with jni?

Possibly, a bit. But while you can eliminate "unwanted" access checks, you lose some of that by the fact that you have to make JNI calls to access the object's innards. By contrast, the implementation of the reflection methods and their calling sequences may be optimized in ways that are not available to a regular JNI method.

(For instance, they may be implemented to directly access the relevant data structures rather than using the platform independent JNI API. Or the JIT compiler may treat native method calls to some "intrinsic" native methods as special cases ... and use a faster calling sequence. Note that this is all hypothetical ... but in some JVMs, the native implementations of some core methods have been given special treatment to make them faster.)


But my advice is that you will get much better performance (by an order of magnitude or more) if you replace the reflective code with regular non-reflective Java code, whether it is hand-written code, code that is generated as source and compiled, or code that is generated as bytecodes. Once you have bytecodes, the JIT compiler will be able to produced optimized native code that will be far faster than using either reflection or JNI.

So rather than replacing reflection with JNI code (and the its associated problems), replace it with something that that uses pure bytecodes.

like image 178
Stephen C Avatar answered Dec 20 '25 17:12

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!