Skip to content

Instantly share code, notes, and snippets.

@aigor
Last active September 19, 2016 13:37
Show Gist options
  • Select an option

  • Save aigor/c9ec1ce8d7fce5d94f9fd6854e7c74e9 to your computer and use it in GitHub Desktop.

Select an option

Save aigor/c9ec1ce8d7fce5d94f9fd6854e7c74e9 to your computer and use it in GitHub Desktop.
Java Memory Consumption per Object
package org.aigor;
/**
* Java Memory Consumption per Object
*
* Based on article:
* http://www.javaworld.com/article/2077496/testing-debugging/java-tip-130--do-you-know-your-data-size-.html
* By Vladimir Roubtsov
*/
public class MemoryTest {
private static final Runtime s_runtime = Runtime.getRuntime ();
public static void main (String [] args) throws Exception
{
// Warm up all classes/methods we will use
runGC ();
usedMemory ();
// Array to keep strong references to allocated objects
final int count = 100000;
Object [] objects = new Object [count];
long heap1 = 0;
// Allocate count+1 objects, discard the first one
for (int i = -1; i < count; ++ i)
{
Object object = null;
// Instantiate your data here and assign it to object
object = new Object ();
//object = new Integer (i);
//object = new Long (i);
//object = new String ();
//object = new byte [128][1];
//object = generateString(0, 1);
// int stringCount = 100000;
// int stringLength = 10;
// object = new ArrayList<>(stringCount);
// for (int j = 0; j < stringCount; j++){
// ((List)object).add(generateString(stringLength, i));
// }
if (i >= 0)
objects [i] = object;
else
{
object = null; // Discard the warm up object
runGC ();
heap1 = usedMemory (); // Take a before heap snapshot
}
}
runGC ();
long heap2 = usedMemory (); // Take an after heap snapshot:
final int size = Math.round (((float)(heap2 - heap1))/count);
System.out.println ("'before' heap: " + heap1 +
", 'after' heap: " + heap2);
System.out.println ("heap delta: " + (heap2 - heap1) +
", {" + objects [0].getClass () + "} size = " + size + " bytes");
for (int i = 0; i < count; ++ i) objects [i] = null;
objects = null;
}
private static void runGC () throws Exception {
// It helps to call Runtime.gc()
// using several method calls:
for (int r = 0; r < 4; ++ r) _runGC ();
}
private static void _runGC () throws Exception {
long usedMem1 = usedMemory (), usedMem2 = Long.MAX_VALUE;
for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++ i)
{
s_runtime.runFinalization ();
s_runtime.gc ();
Thread.currentThread ().yield ();
usedMem2 = usedMem1;
usedMem1 = usedMemory ();
}
}
private static long usedMemory () {
return s_runtime.totalMemory () - s_runtime.freeMemory ();
}
private static String generateString(int length, int start){
char[] chars = new char[length];
for (int i = 0; i < length ; i++){
chars[i] = (char) (i + start);
}
return new String(chars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment