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

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

For class

public class TestClass {
    Integer r=9;
}

allocated memory size is 5152 bytes in a 32-bit JVM

where for

public class TestClass1 {

    Integer i=new Integer(1);

}

memory size is 32 bytes.

why less memory is allocated for class TestClass1?

+3
source share
5 answers

Line:

Integer r = 9;

actually becomes:

Integer r = Integer.valueOf(9);

due to autoboxing that retrieves a cached Integer object. If you check the JLS section 5.1.7 in Boxing Conversions, it states that Integer values ​​between -128 and 127 are cached. In practice, the first call Integer.valueOf()(which includes auto-boxing events) initializes a cache that can take into account different amounts of memory.

+2
source

?

, JVM TestClass1, ,

+1

Integer.valueOf, .

Integer r = 9;
+1
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;
  }

}
0

: TestClass1?

krock,

Integer i = 9; 

Integer i = Integer.valueOf(9);  

, .

-128 127, 255 , (new Integer(i)). .

  • i = new Interger(9); - Integer,
  • i = 9; - 255 Integer .

FYI: . , -128 , 127.

0
source

All Articles