I have a small java test class with only one member variable.. and that variable is a String. I have an ArrayList into which I add a lot of objects of this class. I see that the heap used is ~6 times the data that I add to it). Is there any way to optimize this OR is using an ArrayList a problem in this case.
code:
public class testheap
{
String regionId;
testheap(String s) {
this.regionId = s;
}
public static void main(String[] args) throws Exception
{
ArrayList<testheap> regList = new ArrayList<testheap>(10000);
System.out.println("just Before looping");
printHeapSizes();
//looping
int i = 0;
while (i++ < 2500000) {
if (i%500000 == 0) printHeapSizes(); // print heap sizes every 500000th iteration
testheap reg = new testheap("abcd");
regList.add(reg);
}
System.out.println("end of loop");
printHeapSizes();
public static void printHeapSizes() {
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
//long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
long usedSize = heapSize - heapFreeSize;
System.out.println("total:"+heapSize+" Freesize:"+heapFreeSize + " USED:"+usedSize);
End of code