一、測試代碼
public class ListPerformanceTest {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 1000000; ++i) {
arrayList.add(i);
linkedList.add(i);
}
test1(arrayList);
test2(arrayList);
test3(arrayList);
test1(linkedList);
test2(linkedList);
test3(linkedList);
}
//for循環測試
public static void test1(List<Integer> list) {
long start = System.currentTimeMillis();
for (int i = 0; i < list.size(); ++i) {
int num = list.get(i);
}
long end = System.currentTimeMillis();
System.out.println("test1 : " + (end - start));
}
//iterator測試
public static void test2(List<Integer> list) {
long start = System.currentTimeMillis();
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
int num = (Integer) iterator.next();
}
long end = System.currentTimeMillis();
System.out.println("test2 : " + (end - start));
}
//for each測試
public static void test3(List<Integer> list) {
long start = System.currentTimeMillis();
for (Integer integer : list) {
int num = integer;
}
long end = System.currentTimeMillis();
System.out.println("test3 : " + (end - start));
}
}
二、ArrayList遍歷性能比較(時間單位:微秒)
size | 10 | 100 | 1,000 | 10,000 | 100,000 | 1,000,000 |
---|---|---|---|---|---|---|
for循環 | 0 | 0 | 1 | 2 | 10 | 13 |
Iterator | 1 | 0 | 0 | 2 | 11 | 14 |
for each | 0 | 0 | 0 | 2 | 11 | 12 |
三、LinkedList遍歷性能比較(時間單位:微秒)
size | 10 | 100 | 1,000 | 10,000 | 100,000 | 1,000,000 |
---|---|---|---|---|---|---|
for循環 | 0 | 0 | 3 | 74 | 8656 | >15min |
Iterator | 1 | 1 | 1 | 2 | 4 | 26 |
for each | 0 | 0 | 1 | 3 | 4 | 29 |
四、總結
- 對於ArrayList,無論size是多大,耗時都差不多,選擇哪種方式都一樣
- for each內部其實也是用iterator實現的,所以不管是ArrayList還是LinkedList,iterator和for each的性能都差不多
- 由於LinkedList每次get的時候,都得從開始位置查找,所以遍歷的的性能會很慢
- 綜合來看,建議用for each,代碼簡潔,性能也不差
五、參考資料
https://blog.csdn.net/dengnanhua/article/details/64692191
https://blog.csdn.net/xyc_csdn/article/details/69683799