
在閱讀ArrayList的源碼時(shí),你會(huì)發(fā)現(xiàn)這樣一個(gè)接口:RandomAccess。接下來(lái)讓我們探索一下這個(gè)接口。
首先,這是一個(gè)標(biāo)識(shí)性接口,不包含實(shí)際方法。官方API中的介紹如下:
Marker interface used by List implementations to indicate that
they support fast (generally constant time) random access. The primary
purpose of this interface is to allow generic algorithms to alter their
behavior to provide good performance when applied to either random or
sequential access lists.
也就是說(shuō),這個(gè)接口在List具體實(shí)現(xiàn)中的主要作用是用來(lái)指出該實(shí)現(xiàn)支持快速隨機(jī)訪問(wèn),從而,可以使得某些通用算法可以根據(jù)某些實(shí)現(xiàn)是否支持快速隨機(jī)訪問(wèn)來(lái)修改算法行為以提高性能。
官方API中還特別指出,實(shí)現(xiàn)了該接口的List的具體實(shí)現(xiàn),使用for循環(huán)迭代的速度要遠(yuǎn)遠(yuǎn)高于Iterator循環(huán)。
As a rule of thumb, aList implementation should implement this interface if, for typical instances of the class, this loop:
? for (int i=0, n=list.size(); i < n; i++)
list.get(i);
? for (Iterator i=list.iterator(); i.hasNext(); )
i.next();
我們對(duì)ArrayList的for遍歷和Iteraotr的遍歷做一個(gè)簡(jiǎn)單測(cè)試,我們使用數(shù)據(jù)量為1000000的ArrayList,并遍歷10000次,并計(jì)算耗時(shí)。從計(jì)算結(jié)果看,當(dāng)數(shù)據(jù)量越大時(shí),for遍歷的時(shí)間優(yōu)勢(shì)越高。因此,我們?cè)谔幚泶髷?shù)據(jù)并要求高性能時(shí),這也是值得注意的一個(gè)點(diǎn)。
public static long arrayFor() {
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 1000000; i++) {
list.add(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < list.size(); j++) {
Object num = list.get(j);
}
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static long arrayIterator() {
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 1000000; i++) {
list.add(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
}
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static void main(String[] args) {
long time1 = arrayFor();
long time2 = arrayIterator();
System.out.println("ArrayList for循環(huán)所用時(shí)間 = " + time1 + " ms");
System.out.println("ArrayList 迭代器所用時(shí)間 = " + time2 + " ms");
}
結(jié)果輸出:
ArrayList for循環(huán)所用時(shí)間 = 8 ms
ArrayList 迭代器所用時(shí)間 = 474 ms
Process finished with exit code 0
每日學(xué)習(xí)筆記,寫于2020-06-02 星期二