Created
July 28, 2013 22:34
-
-
Save ersiner/6100545 to your computer and use it in GitHub Desktop.
Java Integer Caching and Autoboxing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package boxingtest; | |
import java.util.Scanner; | |
public class BoxingTest | |
{ | |
public static void main(String[] args) | |
{ | |
Integer[] ints = new Integer[100000]; | |
for (int i = 0; i < ints.length; i++) | |
{ | |
// Integer initializ // Test - count size for java.lang.Integer | |
// ints[i] = new Integer(i); // T1 - 100003 1600048 // Always creates new instance | |
// ints[i] = new Integer(1); // T2 - 100003 1600048 // Always creates new instance | |
// ints[i] = Integer.valueOf(i); // T3 - 100131 1602096 // Triggers Integer cache | |
// ints[i] = Integer.valueOf(1); // T4 - 259 4144 // Triggers Integer cache | |
// ints[i] = i; // T5 - 100131 1602096 // Triggers Integer cache via valueOf() | |
// ints[i] = 1; // T6 - 259 4144 // Triggers Integer cache via valueOf() | |
} | |
System.out.println("Run 'jmap -histo:live <jpid>' and press Enter..."); | |
new Scanner(System.in).nextLine(); | |
// Keep a ref to ints to prevent them from being GCed during jmap. | |
System.out.format("Allocated %d Integers.%n", ints.length); | |
/** | |
* NOTE: Use -Djava.lang.Integer.IntegerCache.high=N to alter the Integer cache range. | |
* Default highest value is 127. | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment