開發日常小結(31):陣列array與列表ArrayList的遍歷效能比較與分析
2018年10月03日
目錄
測試結論
Java兩個常用的資料結構進行效能的比較,發現ArrayList和array還是相差較大的,陣列的遍歷時間遠遠小於ArrayList。
測試例子
import java.util.ArrayList; public class testCompareArrayAndList { /** * @param args */ public static void main(String[] args) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); //新增元素 for(int i =0;i< 11999999;i++){ arrayList.add(i); } //list => array Integer[] array = arrayList.toArray(new Integer[arrayList.size()]); long currentTimeMillis1 = System.currentTimeMillis(); for(Integer i :array){} long currentTimeMillis2 = System.currentTimeMillis(); System.out.println("遍歷陣列耗費時間: "+(currentTimeMillis2 - currentTimeMillis1)+" ms"); currentTimeMillis1 = System.currentTimeMillis(); for(Integer i : arrayList){} currentTimeMillis2 = System.currentTimeMillis(); System.out.println("遍歷列表耗費時間: "+(currentTimeMillis2 - currentTimeMillis1)+" ms"); } }
console:
遍歷陣列耗費時間: 2 ms 遍歷列表耗費時間: 39 ms
效能分析
1)陣列Array:
2)列表ArrayList:
2.1 建構函式
一、初始化設定容量
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
二、無參建構函式
/** * Constructs an empty list with an initial capacity of ten. */
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
三、初始化元素
/** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
2.2 成員變數
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
private transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
1)elementData : 記憶體實際儲存元素是一個數組,即ArrayList是對陣列的一個封裝;
2)size:ArrayList的實際長度;
2.3 add 方法(佇列末尾插入一個元素 / 佇列特定位置插入一個元素)
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
2.4 remove方法(刪除指定位置的元素 / 刪除某個元素)
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
2.5 get 方法
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
實際返回的是陣列的某個元素。
以上是對原始碼的一些走讀總結。