環(huán)球消息!基于ArrayList初始化長度的作用及影響
時間:2023-06-24 16:42:40
目錄
一、有無初始容量的區(qū)別二、initialCapacity != list.size()總結平時寫代碼都直接寫
【資料圖】
Listlist = new ArrayList<>();
由于公司做政.府項目,對并發(fā)和響應沒有太苛刻的要求,平時就沒有考慮到這一塊。
今天看同事代碼在new ArrayList<>()的時候帶入初始容量,于是好奇百度一下,講結果記錄下來。
一、有無初始容量的區(qū)別
/**
? ? ?* The maximum size of array to allocate.
? ? ?* Some VMs reserve some header words in an array.
? ? ?* Attempts to allocate larger arrays may result in
? ? ?* OutOfMemoryError: Requested array size exceeds VM limit
? ? ?*/
? ? private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
? ??
?? ?/**
? ? ?* Default initial capacity.
? ? ?*/
? ? private static final int DEFAULT_CAPACITY = 10;
?? ?/**
? ? ?* 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
? ? ?* will be expanded to DEFAULT_CAPACITY when the first element is added.
? ? ?*/
? ? transient Object[] elementData; // non-private to simplify nested class access
?? ?/**
? ? ?* Shared empty array instance used for empty instances.
? ? ?*/
? ? private static final Object[] EMPTY_ELEMENTDATA = {};?? ?
?? ?/**
? ? ?* 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) {
? ? ? ? if (initialCapacity > 0) {
? ? ? ? ? ? this.elementData = new Object[initialCapacity];
? ? ? ? } else if (initialCapacity == 0) {
? ? ? ? ? ? this.elementData = EMPTY_ELEMENTDATA;
? ? ? ? } else {
? ? ? ? ? ? throw new IllegalArgumentException("Illegal Capacity: "+
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?initialCapacity);
? ? ? ? }
? ? }
?? ?/**
? ? ?* Increases the capacity to ensure that it can hold at least the
? ? ?* number of elements specified by the minimum capacity argument.
? ? ?*
? ? ?* @param minCapacity the desired minimum capacity
? ? ?*/
? ? private void grow(int minCapacity) {
? ? ? ? // overflow-conscious code
? ? ? ? int oldCapacity = elementData.length;
? ? ? ? int newCapacity = oldCapacity + (oldCapacity >> 1);
? ? ? ? if (newCapacity - minCapacity < 0)
? ? ? ? ? ? newCapacity = minCapacity;
? ? ? ? if (newCapacity - MAX_ARRAY_SIZE > 0)
? ? ? ? ? ? newCapacity = hugeCapacity(minCapacity);
? ? ? ? // minCapacity is usually close to size, so this is a win:
? ? ? ? elementData = Arrays.copyOf(elementData, newCapacity);
? ? }以上是JDK1.8的ArrayList源碼,可以看出,
沒有初始容量的話,在做數(shù)據(jù)操作的時候ArrayList會自己創(chuàng)建容量,JDK1.8默認為10每次擴容后容量為oldCapacity + (oldCapacity >> 1)容量最大值Integer.MAX_VALUE - 8由此可以想到,如果存在上千上萬數(shù)據(jù)量的操作,不初始容量和初始化了合適的容量,處理時間肯定不同,因為初始化和擴容是需要時間的。
測試代碼如下:
public static void main(String[] args) {
? ? final int count = 200 * 10000;
? ? List list = new ArrayList<>();
? ? long begin = System.currentTimeMillis();
? ? for(int i = 0; i < count ; i++) {
? ? ? ? list.add(i);
? ? }
? ? System.out.println("沒有設置ArrayList初始容量: " + (System.currentTimeMillis() - begin) + " ms");
? ? List list2 = new ArrayList<>(10);
? ? long begin2 = System.currentTimeMillis();
? ? for(int i = 0; i < count ; i++) {
? ? ? ? list2.add(i);
? ? }
? ? System.out.println("設置了ArrayList初始容量: " + (System.currentTimeMillis() - begin2) + " ms");
} 輸出:
沒有設置ArrayList初始容量: 96 ms
設置了ArrayList初始容量: 26 ms
分析:
在list.add()方法執(zhí)行時,先調(diào)用ArrayList的:
/**
?* Appends the specified element to the end of this list.
?*
?* @param e element to be appended to this list
?* @return true (as specified by {@link Collection#add})
?*/
public boolean add(E e) {
? ? ensureCapacityInternal(size + 1); ?// Increments modCount!!
? ? elementData[size++] = e;
? ? return true;
}進入方法:
private void ensureCapacityInternal(int minCapacity) {
? ? ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
再往下:
private static int calculateCapacity(Object[] elementData, int minCapacity) {
? ? if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {// 第一次add的時候,都會走這一步
? ? ? ? return Math.max(DEFAULT_CAPACITY, minCapacity);//初始化容量小于默認值10都會取10,反之取自定義的容量
? ? }
? ? return minCapacity;
}擴容方法:
private void ensureExplicitCapacity(int minCapacity) {
? ? modCount++;
? ? // overflow-conscious code
? ? if (minCapacity - elementData.length > 0)
? ? ? ? grow(minCapacity);
}
grow():
/**
?* Increases the capacity to ensure that it can hold at least the
?* number of elements specified by the minimum capacity argument.
?*
?* @param minCapacity the desired minimum capacity
?*/
?private void grow(int minCapacity) {//minCapacity是當前容量,比如,默認容量下,add一次后就是10+1
? ? // overflow-conscious code
? ? int oldCapacity = elementData.length;
? ? int newCapacity = oldCapacity + (oldCapacity >> 1);
? ? if (newCapacity - minCapacity < 0)
? ? ? ? newCapacity = minCapacity;
? ? if (newCapacity - MAX_ARRAY_SIZE > 0)
? ? ? ? newCapacity = hugeCapacity(minCapacity);
? ? // minCapacity is usually close to size, so this is a win:
? ? elementData = Arrays.copyOf(elementData, newCapacity);
}總結:
建議初始化容量,減少系統(tǒng)初始化容量的耗時;初始化容量不是越大越好,跟系統(tǒng)配置相關,因為要開辟內(nèi)存。如果能確定add的總數(shù),以總數(shù)作為初始容量效率最高,但這種場景太少了。最佳的設置要兼顧內(nèi)存空間和擴容次數(shù),我也沒有找到最優(yōu)解,歡迎大佬補充。盡管不知道初始化多少最快,但是初始化比未初始化快,并且有限的數(shù)據(jù)量下,設置不同initialCapacity的差距不大。最終,我建議大家初始化容量,并且就寫10(<=10都一樣,看自己喜好)。上例不同大小初始容量的耗時:
| initialCapacity | time |
|---|---|
| 未初始化 | 96 |
| <=10 | 26 |
| 100 | 26 |
| 1000 | 23 |
| 10000 | 648 |
| 100000 | 24 |
| 1000000 | 18 |
| 10000000 | 609 |
二、initialCapacity != list.size()
public static void main(String[] args) {
? ? List list = new ArrayList<>(10);
? ? list.set(0, 666);
} console:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.set(ArrayList.java:448)
at top.chengsw.demo.test.ListTest.main(ListTest.java:25)
此時,list.size() = 0。
也就是說,該構造方法并不是將ArrayList()初始化為指定長度,而是指定了其內(nèi)部的Object數(shù)組的長度,也就是其容量。
當我們調(diào)用size()時,返回的是其實際長度,而非容量大小。
對超出ArrayList長度的部分進行訪問或賦值操作時也會造成訪問越界,盡管它的容量大小足夠。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關稿件
環(huán)球消息!基于ArrayList初始化長度的作用及影響
SpringBoot?spring.factories加載時機分析_今日熱搜
測運勢2022年運勢免費,紫微免費算2022年運勢|環(huán)球觀察
觀察:每日熱聞!今日熱門!北京市教委:高溫天氣下合理調(diào)整學生室外活動時間 根據(jù)實際情況采取減課或停課措施 熱點評_全球播資訊 全球簡訊 每日觀點
新資訊:關系戶來了?勇士新秀的經(jīng)紀人竟然是勇士總經(jīng)理的親弟弟?
享譽:哈爾濱專業(yè)治療疤痕醫(yī)院排名[大膽公開]哈爾濱哪家醫(yī)院無痕祛疤好|當前消息
強化審判能力建設 延伸司法保障職能 ——新疆知識產(chǎn)權保護水平穩(wěn)步提升 天天精選
【短訊】“瓦格納”首領稱其部隊已進入俄境內(nèi)!一文梳理這場“叛亂”經(jīng)過……
中國經(jīng)濟中長期前景POLL(2023年5月/PB):經(jīng)濟、政策雙平穩(wěn)成新主流預期
環(huán)球新動態(tài):南京市醫(yī)保局用新思想指引南京醫(yī)保新實踐
威觀寧夏:保險賠付1400萬很多嗎?對于普通人來說,購買商業(yè)保險是最簡單有效的抵御風險的行為吧?
【世界播資訊】年銷粽子600萬個!古老“粽子村”里的變與不變
范丞丞的“自私”,讓觀眾看清白鹿的為人,《跑男》因此話題出圈 每日視點
世界熱資訊!移動硬盤格式化后能恢復數(shù)據(jù)嗎(請將磁盤插入可移動磁盤)
古裝廠牌到全能玩家,年均爆款的西嘻影業(yè)提供了影視公司的生存法
買手機就選16+512G大內(nèi)存,這3款都是驍龍8+芯片,關鍵價格還不貴
突發(fā)!國泰航空一客機突發(fā)故障,11人逃生途中受傷送醫(yī)!女乘客還原驚恐一幕:有人打電話給父母一直哭,有一個媽媽抱著孩子一直說對不起……


