這依賴於JVM。我嘗試過的Oracle JVM版本(1.6.0_41和1.7.0_09)默認情況下不會執行此優化。但是,1.7.0_09確實會在開啓積極優化時執行此操作。
這裏是我進行的測試:
public class Main {
public static int g() {
int n = 100000;
int arr[][] = new int[n][];
for (int i = 0; i < n; ++i) {
try {
arr[i] = new int[100000];
} catch (OutOfMemoryError ex) {
return i;
}
}
return -1;
}
public static void f1() {
int arr[] = new int[1000000];
System.out.println(g());
}
public static void f2() {
int arr[] = new int[1000000];
arr = null;
System.out.println(g());
}
public static void main(String[] argv) {
for (int j = 0; j < 2; ++j) {
for (int i = 0; i < 10; ++i) {
f1();
}
System.out.println("-----");
for (int i = 0; i < 10; ++i) {
f2();
}
System.out.println("-----");
}
}
}
使用JVM 1.7使用默認設置,f1()
一貫內存用完之後3195次迭代,而f2()
持續管理3205次迭代。如果代碼是用Java 1.7.0_09運行與-XX:+AggressiveOpts -XX:CompileThreshold=1
的情況發生了變化:兩個版本都可以做3205次迭代,這說明熱點確實執行在這種情況下,這種優化。 Java 1.6.0_41似乎沒有這樣做。
在我的測試,限制陣列的範圍有作爲設定參考null
相同的效果,而且也許應該是首選,如果你覺得你應該幫助JVM收集陣列儘快。
來源
2013-03-05 20:40:13
NPE
。 – Cubic 2013-03-05 20:32:27
你可以用括號括住代碼。 – MikeTheLiar 2013-03-05 20:32:41
'data = null'使其有資格被垃圾收集。 – 2013-03-05 20:32:42