I recently wrote a small program that extensively uses Collections. And while I was profiling this for memory utilization on my local machine, I found something wierd happening. To measure memory util, I gave sysouts with totalMemory()-freeMemory() (invoked on the Runtime instance).
At the end of a run, I get the following statements on console:
There were 7 iterations of this loop in total. Notice the output in bold.. The memory used upto this point was constant and then there's a sudden spurt of close to 80 Bytes. I have two questions.. 1. Why is the memory usage constant over the first 4 iterations, till the section in bold? I mean, shouldnt there be a progressive increase if any?
You would have to look a little deeper to see what is taking the memory. My bet would be this is typical behavior for collections. Both HashMaps and ArrayLists are initialized to hold some number of records (capacity) and only grow in memory usage when that capacity is reached (the rate and timing of growth for the ArrayList is left as implementation detail, while for HashMap you can control it with the load factor).
What you are seeing in the growth spurt is probably one or both of the collections you are using reaching its capacity and allocating more space for itself.