java對象佔用記憶體大小計算方式,java佔用記憶體
案例一:
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大小:"+((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();}}
結果:
user大小:7.62576 bytes
說明:
Null 物件佔用8個位元組
案例二:
public class User {boolean flag;long id;Date date ;}
運行測試類別結果;
user大小:23.50192 bytes
說明:
boolean 1+ long 8 + 參考型別 Date 4 =13 湊齊8的倍數 =16
16+Null 物件 8 =24
用Java怎測試一個對象所佔的記憶體的大小?
這是一個測試的方法,參考網上的,具體可以看提供給你的網址
package com;
public class Sizeof {
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]
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 {
&......餘下全文>>
怎獲得一個存活的java對象的記憶體佔用大小?
我一般用jProfiler監視軟體,監控程式的運行狀態。你可以看一個對象在運行時建立了多少個,佔了多大的空間,記憶體回收等參數。
你可以試一下