I ported some portions of my Java code to C++ to speed up calculations on Android (this was a physics subroutine). What I found was that the native code runs several times slower than the Java code. I thought maybe something was wrong with the configuration of my project, or maybe with the array handling, so I put a simple loop in the HelloAndroidJni project to test raw speed difference, and got similar results.
Java Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
/* ...generic boilerplate code... */
TextView tv = (TextView) findViewById(R.id.sample_text);
int loopCount = 100000;
//time the native method
long ticks = System.nanoTime();
int result = nativeTest(100000);
long nativeTime = (System.nanoTime() - ticks) / 100000;
//time the Java method
ticks = System.nanoTime();
result = javaTest(100000);
long javaTime = (System.nanoTime() - ticks) / 100000;
//present results
tv.setText("Native=" + nativeTime + "; Java=" + javaTime);
}
The loop in Java:
int javaTest(int count) {
int result = 0;
for (int i = 0; i < count; i++) {
for (int j = 0; j < 100; j++) {
result += 34432; result++;
result -= 34431; result--;
} }
return result;
}
And the C++ code:
JNIEXPORT jint JNICALL
Java_com_fringecode_helloandroidjni_MainActivity_nativeTest(
JNIEnv *env, jobject jThis, jint count) {
int result = 0;
for (int i = 0; i < count; i++) {
for (int j = 0; j < 100; j++) {
result += 34432; result++;
result -= 34431; result--;
} }
return result;
}
The rest of the project is identical to the HelloAndroidJni sample project. The result of a typical run is Native=2580 ms, Java=195 ms. What could be making the native code run so much slower than the Java?
EDIT: Incidentally, the native code runs much faster than Java on the emulator, but on my phone (LG V20 / Snapdragon 820) the native is much slower.