Java unit testing: how to measure memory footprint for method call

前端 未结 6 1090
梦毁少年i
梦毁少年i 2020-12-05 04:36

Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can\'t lead to out-of-memo

6条回答
  •  萌比男神i
    2020-12-05 04:47

    I can think of several options:

    • Finding out how much memory your method requires via a microbenchmark (i.e. jmh).
    • Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. ClassSize. A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies.

    You can also write your own benchmark test which counts memory. The idea is to

    1. Have a single thread running.
    2. Create a new array to store your objects to allocate. So these objects won't be collected during GC run.
    3. System.gc(), memoryBefore = runtime.totalMemory() - runtime.freeMemory()
    4. Allocate your objects. Put them into the array.
    5. System.gc(), memoryAfter = runtime.totalMemory() - runtime.freeMemory()

    This is a technique I used in my lightweight micro-benchmark tool which is capable of measuring memory allocation with byte-precision.

提交回复
热议问题