我有以下用java撰寫的程式,但它占用了大量的CPU使用率。執行此代碼正在執行的作業的更有效方法是什么?
public static ArrayList sample() {
ArrayList arr = new ArrayList();
for (int out = 0; out < 10000; out )
{
for (int in = 0; in < 20000; in ) {
arr.add(out in);
}
}
return arr;
}
uj5u.com熱心網友回復:
由于串列的內容是簡單計算的,因此最好不要將其全部保存在記憶體中,而是動態計算它。為此實作一個專用List的實際上相當容易:
public class ComputedList extends AbstractList<Integer> {
private final int maxOut;
private final int maxIn;
public ComputedList(int maxIn, int maxOut) {
if (((long) maxIn) * maxOut > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
this.maxIn = maxIn;
this.maxOut = maxOut;
}
@Override
public Integer get(int index) {
int out = index / maxIn;
int in = index % maxIn;
return out in;
}
@Override
public int size() {
return maxIn * maxOut;
}
}
鑒于此代碼 anew ComputedList(20000, 10000)將回傳 a List<Integer>,其內容與您的方法回傳的內容完全相同,但需要的記憶體量要少得多(即與輸入值無關的固定量)。
“缺點”是此串列不支持編輯(即set,將拋出) remove,這可能是也可能不是問題。clearUnsupportedOperationException
uj5u.com熱心網友回復:
堆空間錯誤意味著您沒有足夠的記憶體來存盤所有這些值。
如果您需要所有這些,唯一的解決方案是使用 -Xmx 開關增加堆記憶體。
uj5u.com熱心網友回復:
回圈非常有效;問題是您正在創建一個巨大的串列。如果您需要很多專案,則需要更多的堆記憶體。考慮使用其他東西,比如迭代器。
您可以通過以下方式稍微優化:
ArrayList通過傳遞它的最終大小來初始化。這樣可以避免一些內部復制,- 使用陣列而不是
ArrayList避免裝箱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527499.html
標籤:爪哇循环
上一篇:如何將值從thymyleaf發送到視圖中未使用的控制器
下一篇:如何創建一個空的lucene查詢
