I\'ve tried rewriting some Java functions in C++ and called them using JNI. I ob
ID: 654947 • Letter: I
Question
I've tried rewriting some Java functions in C++ and called them using JNI. I observed that it takes longer time to execute the native C++ functions as compared to Java functions, due to the JNI overhead.
As it is widely believed that C++ has certain advantages over Java, I wanted to know whether rewriting some Java code to C++, with a view to improve overall performance of the Java application, a good idea?
If yes, then what parts of the application should be rewritten and how can a Java application use it?
Explanation / Answer
I would advise against it; in the latest releases JVM was improved very much and the performance differences are minimal, for typical production code. Moreover JNI itself is not free from the performance POV and overall you would lose performance rather than achieve more (as you have found out in your case). In addition to this, native code is not safe (you may have corrupt memory), are less portable and harder to debug.
Try to improve performance by classical techniques (better algorithms and data structures, optimization, reduced I/O overhead etc.) and Java techniques (JVM tuning). Only if you have legacy APIs in native code or you need to perform large computation extensive tasks is JNI recommended.
See also Item 54: Use native methods judiciously in Joshua Bloch's Effective Java (2nd edition) for a more advised reference.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.