Java陣列拷貝/複製的效率比較
阿新 • • 發佈:2019-02-12
今天在研究Jlibrtp程式碼時,偶然注意到裡面大量使用了System.arraycopy()這個方法,心想既然是協議實現,那用的方法肯定都是效率最高或較高的了,以前對這個System.arraycopy()僅有個抽象的認識。另外,JDK中對ArrayList的add與remove方法的實現,居然也是用的System.arraycopy(),讓我不由得對其產生“敬意啊”。今天就來動手試一下到底誰的效率高,到底有多高。
C程式設計師們經常討論陣列複製的效率,此類筆試面試題也層出不窮。在Java中,陣列拷貝可以用:1)for迴圈;2)clone方法;3)System.arraycopy()。測試如下:
(1)使用了一個70元素的字串陣列;
(2)每種方法各迴圈拷貝N次。
統計結果如下:
重複1000次 |
10萬 |
100萬 |
500萬 |
|
for迴圈 |
0 |
47 |
484 |
2421 |
clone方法 |
0 |
32 |
250 |
1235 |
System.arraycopy |
0 |
16 |
94 |
437 |
很明顯了,for迴圈最慢,約為clone方法的2倍,約為System.arraycopy的4~5倍;System.arraycopy最快。
PS:System.arraycopy是呼叫的JNI,怪不得。
附測試程式碼:
Java程式碼- package copytest;
- public class ArrayCopyTest
- {
- private static String [] src
- = {"Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa",
"Vvvvvvv", "Bbbb",
"Cccc", "Dddd", "Eddeee",
"FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff",
- "Aaaaaaaaaa", "Vvvvvvv", "Bbbb", "Cccc", "Dddd", "Eddeee", "FFFFFFffffffff"};
- private static String [] dst;
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- System.out.println(forCopy(5000000));
- System.out.println(cloneCopy(5000000));
- System.out.println(systemJNICopy(5000000));
- }
- /**
- * 使用for來複制陣列
- * @param time 迴圈執行的次數
- * @return 執行的總時間
- */
- public static long forCopy(int time)
- {
- long start = System.currentTimeMillis();
- while(time-- > 0)
- {
- int size = src.length;
- dst = new String [size];
- for (int i = 0; i < size; i++)
- {
- dst[i] = src[i];
- }
- }
- long end = System.currentTimeMillis();
- return (end - start);
- }
- public static long cloneCopy(int time)
- {
- long start = System.currentTimeMillis();
- while(time-- > 0)
- {
- dst = (String[])src.clone();
- }
- long end = System.currentTimeMillis();
- return (end - start);
- }
- public static long systemJNICopy(int time)
- {
- long start = System.currentTimeMillis();
- while(time-- > 0)
- {
- int size = src.length;
- System.arraycopy(src, 0, dst, 0, size);
- }
- long end = System.currentTimeMillis();
- return (end - start);
- }
- }