我正在對HashMap,LinkedHashMap插入進行一些性能測試。我正在測試的操作是在插入後在內存中插入和放大。如何在HashMap和LinkedHashMap中插入數據後計算內存中的大小?
我能夠做到的,插入測試也能夠與下面的邏輯來提取size in memory after insertion
以及 -
long myTotalMemoryBefore = Runtime.getRuntime().totalMemory();
/* Fill the hashmap or linkedhashmap */
long myTotalMemoryAfter = Runtime.getRuntime().totalMemory();
long myHashMapMemory = myTotalMemoryAfter - myTotalMemoryBefore;
我有一個包含2個億,他們的這種格式的頻率英語單詞的文本文件 - 在HashMap
hello 100
world 5000
good 2000
bad 9000
...
現在我讀通過該行文件中的行並將其存儲和LinkeddHashMap
所以我能夠與下面測量插入後,在內存中插入性能和大小,以及代碼。
我有,我有兩個方法,一個是HashMap
等爲LinkedHashMap
性能測試,他們都按順序運行,首先HashMap的測試將運行一個單一的類文件,然後LinkedHashMap的測試預訂購運行 -
public void hashMapTest() {
Map<String, String> wordTest = new HashMap<String, String>();
long myTotalMemoryBefore = Runtime.getRuntime().totalMemory();
String line = reader.readLine();
while (line != null && !line.isEmpty()) {
// split the string on whitespace
String[] splittedString = line.split("\\s+");
String split1 = splittedString[0].toLowerCase().trim();
Integer split2 = Integer.parseInt(splittedString[1].trim());
// now put it in HashMap as key value pair
wordTest.put(split1, split2);
line = reader.readLine();
}
long myTotalMemoryAfter = Runtime.getRuntime().totalMemory();
long myHashMapMemory = (myTotalMemoryAfter - myTotalMemoryBefore)/1024;
System.out.println(myHashMapMemory);
}
public void linkedHashMapTest() {
Map<String, String> wordTest = new LinkedHashMap<String, String>();
long myTotalMemoryBefore = Runtime.getRuntime().totalMemory();
String line = reader.readLine();
while (line != null && !line.isEmpty()) {
// split the string on whitespace
String[] splittedString = line.split("\\s+");
String split1 = splittedString[0].toLowerCase().trim();
Integer split2 = Integer.parseInt(splittedString[1].trim());
// now put it in LinkedHashMap as key value pair
wordTest.put(split1, split2);
line = reader.readLine();
}
long myTotalMemoryAfter = Runtime.getRuntime().totalMemory();
long myLinkedHashMapMemory = (myTotalMemoryAfter - myTotalMemoryBefore)/1024;
System.out.println(myLinkedHashMapMemory); // this is coming as zero always or negative value
}
還有我看到一個很奇怪的問題 - 對於HashMap的性能測試中,我可以看到myHashMapMemory
中有一定的價值,但在myLinkedHashMapMemory
變量,它總是零或負值。
任何想法爲什麼會發生這種情況,以及如何避免這個問題?一般來說,爲什麼我看到零或負值?
我們可以從命令行傳遞這個參數嗎?'-XX:-UseTLAB',因爲我將從命令提示符運行我的可運行jar?而且,我應該使用freeMemory而不是totalMemory? – john
1)是的,java -XX ....; 2)freeMemory在我的簡單情況下是可以的,但最好使用usedMemory = runtime.totalMemory() - runtime.freeMemory()) –