Java performance tip: Think about your container sizes

Take a look at this javadoc entry and then think about what happens if you create many thousands of HashMaps with only 1 or 2 entries in them.

Our work application has a very large number of objects to which you can attach attributes. We use HashMaps for these. Many of them have no attributes and were just getting their HashMap with a new HashMap() call. In order to investigate just why our application was eating up so much memory (relatively speaking. It still isn’t competing with netbeans, firefox, etc). I opened it up in the profiler, saw that of that memory usage the lion’s share of it was from HashMaps. I’ve now changed the code so they’re being given an initial capacity of 1. Things are much happier now.

This is basically just a heads up – if you’re using a lot of a container type which lets you specify an initial capacity (HashMap, HashSet and ArrayList, for example), give it at least some thought rather than using the default. If you only have a few or they’re purely transient it doesn’t really matter. Even if they’re many and long lived you don’t need to worry about getting it exactly right, but a little tuning can save you from a lot of the memory bloat that is common in Java applications.

This entry was posted in programming and tagged , on by .