开发者

Is there any difference in memory allocation using new opeartor in java wrapper class?

开发者 https://www.devze.com 2023-02-16 18:25 出处:网络
Is there any difference in memory allocation using new opeartor in java wrapper class? For the class, public class TestClass {

Is there any difference in memory allocation using new opeartor in java wrapper class?

For the class,

public class TestClass {
    Integer r=9;
}

size of memory allocate开发者_如何转开发d is 5152 bytes in 32 bit JVM

where as for

public class TestClass1 {

    Integer i=new Integer(1);

}

size of memory is 32 bytes.

why there is less memory allocation for class TestClass1?


The line:

Integer r = 9;

actually becomes:

Integer r = Integer.valueOf(9);

due to autoboxing, which retrieves a cached Integer object. If you check the JLS Section 5.1.7 on Boxing Conversions it states that Integer values between -128 an 127 are cached. In practice, the first call to Integer.valueOf() (which includes autoboxing occurrences) will initialize the cache which may account for a different memory footprint.


How are you measuring this?

It seems to me that the JVM would be well within its rights to optimise away the Integer in TestClass1, since its never used, leaving a reference to an empty class


Integer.valueOf which doesn't always create a new object. Thats why memory allocation is different for

Integer r = 9;


public class Sizer {

  public static void main(String [] args) throws Exception {
    Runtime r = Runtime.getRuntime();

    // Pre-instantiate variables
    long memoryBefore = 0;
    long memoryAfter = 0;
    int loops = 10;

    runGC(r, loops);
    memoryBefore = getMemoryUsage(r);

//     Long lo = new Long(1);
    TestClass in = new TestClass(); 

    runGC(r, loops);
    memoryAfter = getMemoryUsage(r);

    System.out.println("Diff in size is " + (memoryAfter - memoryBefore));
  }

  public static void runGC(Runtime r, int loops) throws Exception {
    for(int i=0; i<loops; i++) {
      r.gc();
      Thread.sleep(2000);
    }
  }

  public static long getMemoryUsage(Runtime r) throws Exception {
    long usedMemory = r.totalMemory() - r.freeMemory();
    System.out.println("Memory Usage: " + usedMemory);
    return usedMemory;
  }

}


Q: Why there is less memory allocation for class TestClass1?

As already krock mentioned the

Integer i = 9; 

will become

Integer i = Integer.valueOf(9);  

This instruction cause that the cache has to be initialized before you can used it.

The cache contains values from -128 to usually 127, this give 255 values that has to be initialized (new Integer(i)). And this cause such big memory usage.

Resuming instruction

  • i = new Interger(9); - Will create one Integer object,
  • i = 9; - Will create at least 255 Integer objects and one array.

FYI: The cache initialization does not depend of the boxed value. The cache is also initialized when you are boxing values lower then -128 and greater then usually 127.

0

精彩评论

暂无评论...
验证码 换一张
取 消