如何在HashMap中插入后在内存中查找大小?

AKI*_*WEB 2 java hashmap performance-testing

我正在对HashMap插入进行一些性能测试.我正在测试的操作是在插入后插入,读取和在内存中的大小.

我可以做,插入和读取测试,但不知道如何找出size in memory after insertion-

我有一个文本文件,其中包含200万个英文单词,其频率为此格式 -

hello 100
world 5000
good 2000
bad 9000
...
Run Code Online (Sandbox Code Playgroud)

现在我逐行读取此文件并将其存储,HashMap以便我可以使用以下代码测量插入性能.

Map<String, String> wordTest = new HashMap<String, String>();

try {
    fis = new FileInputStream(FILE_LOCATION);
    reader = new BufferedReader(new InputStreamReader(fis));

    String line = reader.readLine();
    long startTime = System.nanoTime();
    while (line != null) {
    String[] splitString = line.split("\\s+");
    // now put it in HashMap as key value  pair
    wordTest.put(splitString[0].toLowerCase().trim(), splitString[1].trim());

    line = reader.readLine();
    }
    long endTime = System.nanoTime() - startTime;
    System.out.println("Insertion Time: " +TimeUnit.MILLISECONDS.convert(endTime, TimeUnit.NANOSECONDS));
}
Run Code Online (Sandbox Code Playgroud)

现在我想size in memory after insertion在上面衡量一下HashMap.

从这个链接看后我基本上感到困惑 - https://github.com/jpountz/tries/wiki/Benchmark.在这个链接中他们有size in memory after insertion但不确定它是什么意思以及他们如何计算它?有什么方法可以用Java做同样的事情吗?

Ale*_*lev 15

再一次,我希望注意,如果您使用Unsafe挖掘VM的头脑,可以获得Java对象的确切内存占用量测量.有很多项目使用这种技术,其中一个是jol,可以在OpenJDK中使用(这意味着它也适用于Oracle JDK).例如,这是显示ArrayList与LinkedList脚印的可运行示例:

Running 64-bit HotSpot VM.
Using compressed references with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

java.util.ArrayList instance footprint:
 COUNT   AVG   SUM DESCRIPTION
     1  4952  4952 [Ljava.lang.Object;
  1000    16 16000 java.lang.Integer
     1    24    24 java.util.ArrayList
  1002       20976 (total)


java.util.LinkedList instance footprint:
 COUNT   AVG   SUM DESCRIPTION
  1000    16 16000 java.lang.Integer
     1    32    32 java.util.LinkedList
  1000    24 24000 java.util.LinkedList$Node
  2001       40032 (total)
Run Code Online (Sandbox Code Playgroud)

您可以将jol作为依赖项,并将HashMap实例提供给它.