0
点赞
收藏
分享

微信扫一扫

开发日常小结(31):数组array与列表ArrayList的遍历性能比较与分析


2018年10月03日

目录

​​测试结论​​

​​测试例子​​

​​性能分析​​

​​1)数组Array:​​

​​2)列表ArrayList:​​

​​2.1 构造函数​​

​​2.2 成员变量​​

​​2.3 add 方法(队列末尾插入一个元素 / 队列特定位置插入一个元素)​​

​​2.4 remove方法(删除指定位置的元素 / 删除某个元素)​​

​​2.5  get 方法​​

 

测试结论

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:

参考文章:​​《java数组详解》​​

 

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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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);
}

实际返回的是数组的某个元素。

 

以上是对源码的一些走读总结。

 

举报

相关推荐

0 条评论