2021年5月7日星期五

How Android Runtime compiles Java more efficiently than the CLang C/С++ compiler (Android NDK)?

I was absolutely sure that C\C++ native code will run faster than Java code. And it is. My simple C/C++ benchmark (random arithmetic operations on int array) runs 5-7 times faster than the same Java code on an old tablet (Samsung Galaxy Tab E - Android 4.4.4 - Dalvik VM), but slower on recent devices with ART Prestigio K3 Muze (Android 8.1) & Samsung S21 Ultra (Android 11).

Why Android Runtime compiled code runs faster than native C/C++ code (Android NDK / JNI)?

Java code:

public void calculateJava(int size) {      int[] array = new int[size];      int sum = 0;        for (int i=0; i<size; i++) {          array[i] = i;          for (int j=0; j<size; j++) {              sum += array[i] * array[j];              sum -= sum / 3;         }      }       }  

C/C++ code (JNI):

extern "C" JNIEXPORT void JNICALL Java_com_axiom_firstnative_MainActivity_calculateNative(          JNIEnv* env,          jobject,          jint size) {        int* array = new int[size];      jint sum = 0;        for (jint i=0; i<size; i++) {          array[i] = i;          for (jint j=0; j<size; j++) {              sum += array[i] * array[j];              sum -= sum / 3;          }      }        // delete[] array;  }    

OnClick (Java)

     long startTime = System.nanoTime();       calculateNative(4096);       long nativeTime = System.nanoTime() - startTime;                         startTime = System.nanoTime();       calculateJava(4096);       long javaTime = System.nanoTime() - startTime;                         String report = "VM:" + System.getProperty("java.vm.version")                          + "\n\nC/C++: " + nativeTime                           + "ns\nJava: " + javaTime + "ns\n"                          + "\nJava to C/C++ ratio "                           + ((double) javaTime / (double) nativeTime);    

Results:

Samsung Galaxy Tab E (Android 4.4.4) - Java time: 2166748ns , C/C++ time: 396729 ns (C/C++ 5 times faster)

but

Prestigio K3 Muze (Android 8.1) on first start - Java time:3477001ns, C/C++ time: 547692ns (C/C++ 6 times faster), but after warm up Java runs 30-40% faster.

Samsung Galaxy S21 Ultra (Android 11) - Java time: 111000ns, C/C++ time: 121269ns (Java 9% faster on first start and 40-50% faster after warm up!!!)

Question:

How Android Runtime compile more efficient native code than CLang compiler?

Is there any performance advantage writing native C/C++ code on recent Android OS versions?

https://stackoverflow.com/questions/67423616/how-android-runtime-compiles-java-more-efficiently-than-the-clang-c-%d0%a1-compiler May 07, 2021 at 01:58AM

没有评论:

发表评论