我正在对 HashMap、LinkedHashMap 插入进行一些性能测试。我正在测试的操作是插入和插入后内存中的大小。
我能够插入测试,并且还能够使用以下逻辑提取插入后内存中的大小
-
long myTotalMemoryBefore = Runtime.getRuntime().totalMemory();
/* Fill the hashmap or linkedhashmap */
long myTotalMemoryAfter = Runtime.getRuntime().totalMemory();
long myHashMapMemory = myTotalMemoryAfter - myTotalMemoryBefore;
我有一个文本文件,其中包含 200 万个英语单词,其频率采用这种格式 -
hello 100
world 5000
good 2000
bad 9000
...
现在我正在逐行读取此文件并将其存储在 HashMap
和 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
,然后例如这个
Runtime rt = Runtime.getRuntime();
long m0 = rt.totalMemory() - rt.freeMemory(); //used memory
Object obj = new Object();
long m1 = rt.totalMemory() - rt.freeMemory();
System.out.println(m1 - m0);
将显示内存中 java.lang.Object 的正确大小 - 在我的情况下为 16 字节
关于java - HashMap和LinkedHashMap中插入数据后如何计算内存中的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100477/