不過找到的內容通常都是說
ArrayList因為是用陣列索引值來紀錄
因此在檢索的時候可以很快取得對應位置
但是在插入或刪除的時候為了其後續的資料搬移則會影響效能
而LinkedList因為用的是節點之間的pre post來記錄
因此與ArrayList相反的是檢索耗時
而插入或刪除只需要將其pre post的指標指到另一個新節點
故其在插入或刪除的效能會來的比ArrayList要好
就在剛才做了一個實驗
分別將ArrayList和LinkedList都先置入50萬筆Integer的資料
接下來用list.add(int index, new Integer())的方式隨機置入1萬筆資料
結果如下圖所示
LinkedList完全就沒有比ArrayList快,反而慢了五倍以上
接下來用list.get(random.nextInt())隨機挑選兩集合中的物件
一樣是反覆1萬次,結果如下
可以看出來ArrayList在取得索引位置確實比插入來的快許多
而LinkedList一樣是..........
原因或許是因為ArrayList搬移複製資料的速度非常之快以至於對效能影響不大
而LinkedList光是要找出某個指定位置的值就不知道要靠pre post尋到何時了
等到他費了好大的功夫終於找到所要的位置時
才正要開心的將其pre post指標置換時
才正要開心的將其pre post指標置換時
ArrayList早八百年前就結束了工作!!!
以下為測試原始碼
import java.util.*; public class LinkedListVSArrayList{ public static void main(String[] args){ int VALUE_NUMBER = 500000; ArrayList<Integer> array = new ArrayList<Integer>(); LinkedList<Integer> linked = new LinkedList<Integer>(); for(int i=0; i<VALUE_NUMBER; i++){ Integer integer = new Integer(i); array.add(integer); linked.add(integer); } //ArrayList computeTimeWaste(array, VALUE_NUMBER); //LinkedList computeTimeWaste(linked, VALUE_NUMBER); } public static void computeTimeWaste(List<Integer> list, int VALUE_NUMBER){ Random random = new Random(); int temp = 0; long beforeTime = System.currentTimeMillis(); for(int i=0; i<10000; i++){ //插入 list.add(random.nextInt(VALUE_NUMBER), new Integer(5)); //取得 //temp = list.get(random.nextInt(VALUE_NUMBER)); } long wasteTime = System.currentTimeMillis() - beforeTime; System.out.println(list.getClass().getName() + " random many times: " + wasteTime/1000F); } }