Reputation: 3
Whether I use Long[]
, Integer[]
or ArrayList<Integer>
, why do all of them return the same memory usage?
System.out.println("Memory Usage : " + Runtime.getRuntime().totalMemory()/(1024*1024));
System.out.println("Memory Usage : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/(1024*1024));
//Long[] aa = new Long[70000000];
Integer[] bb = new Integer[70000000];
//ArrayList<Integer> a = new ArrayList<Integer>(70000000);
System.gc();
System.out.println("Memory Usage : " + Runtime.getRuntime().totalMemory()/(1024*1024));
System.out.println("Memory Usage : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/(1024*1024));
Upvotes: 0
Views: 326
Reputation: 1499770
In the above statements Whether i use Long[], Integer[] or ArrayList, why all of them give same memory usage ?
It makes perfect sense. In all cases, you're basically allocating an array which is 70000000 * (size of reference on your JVM). The size of an Integer
reference is the same as the size of a Long
reference, which is the same as the size of an Object
reference. In the ArrayList
case you've got the very small additional overhead of the ArrayList
object itself, but that's pretty small - and easily explained as per Louis's comment.
If you actually populated those arrays, creating instances of Long
and Integer
, then you'd see a difference. Likewise if you created a long[]
vs an int[]
, you'd see a difference.
Upvotes: 6