Memory usage of java objects
Case 1:
User
public class User {}
UserSizeTest
Public class UserSizeTest {static final Runtime runTime = Runtime. getRuntime (); public static void main (String [] args) {final int count = 100000; User [] us = new User [count]; long heap1 = 0; for (int I =-1; I <count; ++ I) {User user = null; user = new User (); if (I> = 0) us [I] = user; else {user = null; heap1 = getUsedMemory () ;}} long heap2 = getUsedMemory (); System. out. println ("user size:" + (float) heap2-heap1)/count + "bytes"); for (int I = 0; I <count; I ++) {us [I] = null;} runTime. gc ();} static long getUsedMemory () {return runTime. totalMemory ()-runTime. freeMemory ();}}
Result:
User size: 7.62576 bytes
Note:
An empty object occupies 8 bytes.
Case 2:
public class User {boolean flag;long id;Date date ;}
Run the test results;
User size: 23.50192 bytes
Note:
Boolean 1 + long 8 + reference type Date 4 = 13 multiple of 8 = 16
16 + null objects 8 = 24