Created
January 2, 2011 04:17
-
-
Save KengoTODA/762273 to your computer and use it in GitHub Desktop.
オブジェクトのサイズを調べる簡単なコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class Test { | |
private Class<?>[] CLASSES = new Class<?>[] { | |
Object.class, | |
HasOneField.class, | |
HasTwoField.class, | |
HasThreeField.class, | |
HasLongField.class, | |
HasTwoLongField.class, | |
HasIntAndLongField.class, | |
HasObjectField.class, | |
HasTwoObjectField.class, | |
HasEightByteField.class, | |
HasNineByteField.class, | |
ArrayList.class | |
}; | |
public static void main(String[] args) { | |
try { | |
for (int i = 0; i < 2; ++i) { | |
new Test().test(i); | |
} | |
} catch (InstantiationException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void test(int i) throws InstantiationException, IllegalAccessException { | |
for (Class<?> c : CLASSES) { | |
System.gc(); | |
long beforeFree = Runtime.getRuntime().freeMemory(); | |
Object instance = c.newInstance(); | |
System.gc(); | |
long afterFree = Runtime.getRuntime().freeMemory(); | |
if (i != 0) { | |
System.out.printf( | |
"%30s,%2d fields,%3d bytes%n", | |
instance.getClass().getName(), | |
c.getDeclaredFields().length, | |
beforeFree - afterFree); | |
} | |
} | |
} | |
static class HasOneField { | |
private int field; | |
} | |
static class HasTwoField { | |
private int field1; | |
private int field2; | |
} | |
static class HasThreeField { | |
private int field1; | |
private int field2; | |
private int field3; | |
} | |
static class HasLongField { | |
private long field1; | |
} | |
static class HasTwoLongField { | |
private long field1; | |
private long field2; | |
} | |
static class HasIntAndLongField { | |
private int field1; | |
private long field2; | |
} | |
static class HasObjectField { | |
private Object field1; | |
} | |
static class HasTwoObjectField { | |
private Object field1; | |
private Object field2; | |
} | |
static class HasNineByteField { | |
private byte field1; | |
private byte field2; | |
private byte field3; | |
private byte field4; | |
private byte field5; | |
private byte field6; | |
private byte field7; | |
private byte field8; | |
private byte field9; | |
} | |
static class HasEightByteField { | |
private byte field1; | |
private byte field2; | |
private byte field3; | |
private byte field4; | |
private byte field5; | |
private byte field6; | |
private byte field7; | |
private byte field8; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment