前言:本系列的主题是平时容易疏忽的知识点,只有基础扎实,在编码的时候才能更注重规范和性能,在出现 bug 的时候,才能处理更加从容。
- private static class IntegerCache {
- static final int low = -128;
- static final int high;
- static final Integer cache[];
- static {
- // high value may be configured by property
- int h = 127;
- String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
- if (integerCacheHighPropValue != null) {
- try {
- int i = parseInt(integerCacheHighPropValue);
- i = Math.max(i, 127);
- // Maximum array size is Integer.MAX_VALUE
- h = Math.min(i, Integer.MAX_VALUE - ( - low) - 1);
- } catch(NumberFormatException nfe) {
- // If the property cannot be parsed into an int, ignore it.
- }
- }
- high = h;
- cache = new Integer[(high - low) + 1];
- int j = low;
- for (int k = 0; k < cache.length; k++) cache[k] = new Integer(j++);
- // range [-128, 127] must be interned (JLS7 5.1.7)
- assert IntegerCache.high >= 127;
- }
- private IntegerCache() {}
- }
- public static void main(String[] args) {
- Integer i1 = new Integer(127);
- Integer i2 = new Integer(127);
- System.out.println(i1 == i2);
- //false
- }
- public static void main(String[] args) {
- Integer i1=127;
- Integer i2=127;
- System.out.println(i1==i2);
- //true
- }
- public static void main(String[] args) {
- Integer i1 = 127;
- }
- public static Integer valueOf(int i) {
- if (i >= IntegerCache.low && i <= IntegerCache.high)
- return IntegerCache.cache[i + (-IntegerCache.low)];
- return new Integer(i);
- }
- public static void main(String[] args) {
- Integer i1 = Integer.valueOf(127);
- Integer i2 = 127;
- System.out.println(i1 == i2);
- //true
- }
- public static void main(String[] args) {
- Integer i1 = 128;
- Integer i2 = 128;
- System.out.println(i1 == i2);
- //false
- }
- // -XX:AutoBoxCacheMax=128
- public static void main(String[] args) {
- Integer i1 = 128;
- Integer i2 = 128;
- System.out.println(i1 == i2);
- //true
- }
- public static void main(String[] args) {
- Integer sum = 0;
- sum = sum + 128;
- }
- public static void main(String[] args) {
- t1();
- t2();
- }
- public static void t1() {
- Long start = System.currentTimeMillis();
- Integer sum = 0;
- for (int i = 130; i < 1000000; i++) {
- sum = sum + i;
- }
- System.out.println(System.currentTimeMillis() - start);
- }
- public static void t2() {
- Long start = System.currentTimeMillis();
- int sum = 0;
- for (int i = 130; i < 1000000; i++) {
- sum = sum + i;
- }
- System.out.println(System.currentTimeMillis() - start);
- }
- // 输出 10 3
来源: http://www.cnblogs.com/-new/p/7428166.html