Tip of the day: where to start with optimizing memory?

In short: open a JXRay report, go over the “red flags” in it, find the one(s) that will give you the biggest bang for the buck and change your code accordingly.

Each JXRay report contains is a list of all possible problems / optimization opportunities, but in each heap dump a given problem may or may not cause much waste. So once you obtained a report, you should first find problems that cause maximum waste (marked with red labels and have biggest overhead), and then see how easy it is to fix each of them. Choose the problem that has the best combination of expected savings and required work, and start with it.

Some factors to consider when estimating the required effort:

  • Do you control the code that manages the bad objects? It’s easy to change your own source files to e.g. intern some duplicate strings – but it may not be possible to do the same trick in a third-party library.
  • How difficult is the problem itself? Adding an .intern() call to strings is usually easy, and so is creating collections with correct capacity, like new HashMap(4); instead of just new HashMap();. But dealing with other problems, such as duplicate objects other than strings or numerous small objects may be less straightforward.
  • Will you get rid of many objects after the optimization? Since GC time is proportional to both size and number of objects to scan, reducing the number of objects, even small ones, such as boxed numbers, can result in surprisingly big improvement of GC time.

To learn more about problems detected by JXRay and possible solutions, check out our articles. We hope your apps will use much less memory soon!

Leave a Reply

Your email address will not be published. Required fields are marked *