Search code examples
javahashmapperformance-testing

How to find size in Memory after insertion in HashMap?


I am working on some performance test on HashMap insertion. Operations on which I am testing are insert, read and size in memory after insertion.

I am able to do, insert and read test but not sure how do I find out size in memory after insertion -

I have a text file which contains 2 million english words with their frequencies in this format -

hello 100
world 5000
good 2000
bad 9000
...

Now I am reading this file line by line and storing it in HashMap so I am able to measure the insertion performance with the below code.

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));
}

Now I would also like to measure size in memory after insertion in my above HashMap.

Basically I am confuse after taking a look from this link - https://github.com/jpountz/tries/wiki/Benchmark. In this link they have size in memory after insertion but not sure what does it mean and how they have calculated it? Is there any way I can do the same thing in Java?


Solution

  • Although using an external tool is a viable solution, the easy Java way is:

    long myTotalMemoryBefore = Runtime.getRuntime().totalMemory();
    
    /* Fill the hash Table */
    
    long myTotalMemoryAfter = Runtime.getRuntime().totalMemory();
    long myHashMapMemory = myTotalMemoryAfter - myTotalMemoryBefore;
    

    The values are in bytes, do divide by 1024 to Kbytes,etc...

    Details here:

    http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#totalMemory%28%29

    and here:

    What are Runtime.getRuntime().totalMemory() and freeMemory()?