Page 178
Optimization 47: JNI to the Rescue Software performance engineering is a delicate task. There are very few blanket statements that apply in all situations. Almost every performance principle depends on context and could easily backfire if applied out of context. The same holds for JNI. As demonstrated earlier, you cannot always trust that JNI execution speed is superior to Java. But you cannot claim the opposite, either, because there are plenty of computational scenarios in which JNI execution speed will leave Java in the dust. We will examine one such example next. Whenever I search for a compute-intensive task in Java, the Date class immediately comes to mind. The conversion of a Date object to a String representation is expensive and slow: Date date = new Date(); … String p = date.toString(); This is why I sometimes refer to Java as a performance minefield. Some computations look and feel extremely simple, yet they may harbor a significant performance cost. In a statement as simple as the one-line Date statement above, there is a world of computational complexity. The visual correspondence between the complexity of the source code and its cost have been broken in higher level languages. An assembly-language programmer would know right away how expensive this computation is because it would take her hundreds of assembly-language instructions to perform this complex conversion from a timestamp to a String object representing a date. This conversion looks pretty simple in C/C++, with the exception that it is a lot faster. Here’s the JNI implementation using the ctime() call in C. First, the Java class definition: class MyJni { … private static native String jctime(); // Native method }; The native implementation is shown below: jstring JNICALL Java_MyJni_jctime(JNIEnv *env, jclass thisClass) { time_t t; char *s; time(&t); s = ctime(&t); return (env->NewStringUTF(s)); } The preceeding is the C/C++ implementation of a native method called jctime() declared for a class called MyJni. This is where the name Java_MyJni_jctime() comes from. If the class MyClass declares a native method myMethod(), the corresponding JNI function name would be Java_MyClass_myMethod(). We contrasted 100,000 iterations of String p = date.ToString(); to the JNI call String p = jctime(); // compute the String rep of (new Date()) Page 179
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services