close
本文節錄自下述的連結,並且加入適當的翻譯與註解:
http://www.vogella.com/tutorials/JavaPerformance/article.html
Java 程式的效能取決於記憶體使用量 (Memory) 與執行所消耗的時間 (Execution Time),而Java處理記憶體主要是使用 Heap and Stack。Java Virtual Mahine (JVM)會記錄所有在Java program中被產生出來的物件,並且記錄在 Heap 中,當物件沒有被 reference 的時候才會被 JVM 清掉,然後釋放物件所佔用的記憶體。Stack則是用來記錄函數呼叫與區域變數的區塊。
JVM 的記憶體大小是可以在初始階段被設定的,可在 JVM 裡面輸入:
-Xms1024m |
設定記憶體為 1024 MB,此設定寫在環境變數下,或者在 Eclipse 程式執行前在 Argument 填入此資訊,這會用另一篇文章介紹。
如何計算 Java program 當下記憶體耗量:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class PerformanceTest { | |
private static final long MEGABYTE = 1024L * 1024L; | |
public static long bytesToMegabytes(long bytes) { | |
return bytes / MEGABYTE; | |
} | |
public static void main(String[] args) { | |
ArrayList list = new ArrayList(); | |
for (int i = 0; i <= 100000; i++) { | |
list.add("1"); | |
} | |
// Get the Java runtime | |
Runtime runtime = Runtime.getRuntime(); | |
// Run the garbage collector | |
runtime.gc(); | |
// Calculate the used memory | |
long memory = runtime.totalMemory() - runtime.freeMemory(); | |
System.out.println("Used memory is bytes: " + memory); | |
System.out.println("Used memory is megabytes: " | |
+ bytesToMegabytes(memory)); | |
} | |
} |
如何計算前後執行的時間差異:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TimeTest1 { | |
public static void main(String[] args) { | |
long startTime = System.currentTimeMillis(); | |
long total = 0; | |
for (int i = 0; i < 10000000; i++) { | |
total += i; | |
} | |
long stopTime = System.currentTimeMillis(); | |
long elapsedTime = stopTime - startTime; | |
System.out.println("執行前後記憶體差異: " + elapsedTime); | |
} | |
} |
全站熱搜