2014-11-05 50 views
3

考慮,其存儲在一個數組項[]長度N.使用了多少個字節?

public class MysteryBox {  // 16B (object overhead) 
    private int N;    // 4B (int) 
    private boolean[] items; // 8B (reference to array) 
         // 24B (header of array) 
         // N (boolean array of size N) 
// 4B for padding 
// 17N (boolean objects, 16B of object metadata, 1B of data equivalent to 1 boolean) 
    ... 
} 

多少字節被用作N的函數(64位存儲器成本模型的布爾類型的 N項類型MysteryBox的目的)?我的答案是否正確?

+1

不是你的問題的直接答案,但可能'java.util.BitSet'可能是存儲這種信息(可能是爲了高效)的好主意。 – 2014-11-05 22:30:32

+0

不應該在64位系統的堆棧上使用64位?還必須加載類元數據,並且該類的每個實例都會消耗堆棧和堆中的內存。 – Hannes 2014-11-05 22:31:01

+0

據我記憶,布爾值被存儲在每個4字節 – njzk2 2014-11-05 22:31:07

回答

0

讓我們試試看!

public static void main(String[] args) 
{ 
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); //This might cause a little bit of error 
    for(int N=1400;N<5000;N+=100) //this is on the stack, so it shouldn't affect us 
    { 
     int[] reserved = new int[1000]; //we'll clear this later 
     MysteryBox box = new MysteryBox(N); 
     int count = 1; 
     while(true) 
     { 
      try 
      { 
       MysteryBox temp = new MysteryBox(N); 
       temp.next = box; //don't worry, this extra variable was subtracted out during analysis 
       box=temp; 
       count++; 
      } 
      catch(java.lang.OutOfMemoryError e) 
      { 
       reserved = null; 
       MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); 
       long maxMemory = heapUsage.getMax(); 
       long usedMemory = heapUsage.getUsed(); 
       System.out.println(N+ " : " + count + " : Memory Use :" + usedMemory + "/" + maxMemory + ""); 
       break; 
      } 
     } 
    } 
} 

結果:每MysteryBox內存的使用是相對於N.內存使用以字節爲單位被1.0052N + 33.84給出非常線性關係(r^2輪爲1)。所以,顯然每個布爾值佔用大約一個字節,其餘所有開銷都佔用大約34個字節。我會讓你猜測開銷是如何分配的。