java對象佔用記憶體大小計算方式,java佔用記憶體

來源:互聯網
上載者:User

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監視軟體,監控程式的運行狀態。你可以看一個對象在運行時建立了多少個,佔了多大的空間,記憶體回收等參數。
你可以試一下
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.