前言
java中的native方法性能到底怎么樣?
第一次寫博客,如果寫的不好,望見諒,煩請指出問題,虛心學習
先說結論,native 方法性能不如java方法
一、native方法?
主要是java語言本身是無法呼叫作業系統提供的一些底層特性,比如打開檔案,創建執行緒;本文不再介紹如何去使用JNI,只談論性能
二、使用步驟
先創建一個具有native方法的類
代碼如下(示例):
public class TestJNI {
public int num1;
static {
System.load("/Users/alex/Library/Java/Extensions/TestJNI.jnilib");
}
/**
int轉string
*/
public native String intToString(int param);
public native int stringToInt(String param);
/**
他的本質也是給num1屬性set值
*/
public native void modifyNum1(int num1);
public void setNum1(int num1) {
this.num1 = num1;
}
}
2.c語言實作
執行命令,編譯成.h檔案,(要注意,如果你的包名很長,那么你要回到你的包起始位置呼叫命令)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "com_Alex_io_jni_TestJNI.h"
/*
* Class: com_Alex_io_jni_TestJNI
* Method: intToString
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_Alex_io_jni_TestJNI_intToString
(JNIEnv *env, jobject o, jint j_int)
{
int c_int = (int)j_int;
if (c_int == 0)
{
return (*env)->NewStringUTF(env,"0");
}
char* str = (char*)malloc(sizeof(char) * 20);
int index = 0;
while(c_int != 0)
{
int tmp = c_int % 10;
str[index++] = tmp + 48;
c_int /= 10;
}
str[index] = '\0';
for(int i = 0,j = index - 1,size = index / 2; i < size;i++,j--)
{
str[i] ^= str[j];
str[j] ^= str[i];
str[i] ^= str[j];
}
return (*env)->NewStringUTF(env,str);
}
/*
* Class: com_Alex_io_jni_TestJNI
* Method: stringToInt
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_Alex_io_jni_TestJNI_stringToInt
(JNIEnv *env, jobject o, jstring j_string)
{
char* s = (char*)(*env)->GetStringUTFChars(env,j_string,0);
int c_num = atoi(s);
return (jint)c_num;
}
/*
* Class: com_Alex_io_jni_TestJNI
* Method: modifyNum1
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_Alex_io_jni_TestJNI_modifyNum1
(JNIEnv *env, jobject o, jint j_int)
{
jclass class = (*env)->GetObjectClass(env,o);
jfieldID id = (*env)->GetFieldID(env,class,"num1","I");
(*env)->SetIntField(env,o,id,j_int);
}
3.前兩個方法主要是int轉string,或int轉string,有興趣可關注下,主要談第三個方法
第三個方法主要是為變數num1進行賦值,我們看下呼叫java方法和native方法賦值的性能如何
,看下測驗代碼
public class MyTest {
public static void main(String[] args) {
TestJNI testJNI = new TestJNI();
// String s = testJNI.intToString(434343220);
// int s = testJNI.stringToInt("1234567890");
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
testJNI.modifyNum1(50);
}
System.out.println("呼叫native method(10w次) 耗時:" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
testJNI.setNum1(50);
}
System.out.println("呼叫java method(10w次) 耗時:" + (System.currentTimeMillis() - start));
System.out.println(testJNI.num1);
}
}
結果:
呼叫native method(10w次) 耗時:25
呼叫java method(10w次) 耗時:1
50
行程已結束,退出代碼 0
總結
可以看出性能差距比較大,native方法主要還是用于一些對于操控作業系統,對記憶體操作的演算法上,通常可以用java實作的,還是不要用native方法,不正確的使用可能會導致記憶體泄漏與性能損失
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/206179.html
標籤:其他
