java Integer.ValueOf(int)和new Integer(int)性能比较
转自 http://blog.youkuaiyun.com/zhongweijian/article/details/5317375
JDK的源码,看看到Integer.ValueOf(int)里面做了什么优化:
- public static Integer valueOf(int i) {
- final int offset = 128;
- if (i >= -128 && i <= 127) { // must cache
- return IntegerCache.cache[i + offset];
- }
- return new Integer(i);
- }
- private static class IntegerCache {
- private IntegerCache(){}
- static final Integer cache[] = new Integer[-(-128) + 127 + 1];
- static {
- for(int i = 0; i < cache.length; i++)
- cache = new Integer(i - 128);
- }
- }
从源代码可以知道,ValueOf对-128~127这256个值做了缓存(IntegerCache),如果int值的范围是:-128~127,在ValueOf(int)时,他会直接返回IntegerCache的缓存给你。
Integer a = 10;
Integer b = 10;
System.out.println(a==b);
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c==d);
Integer e = 200;
Integer f = 200;
System.out.println(e == f);
}
结果是:
true
false
false
因为:java在编译的时候 Integer a = 10; 被翻译成-> Integer a = Integer.valueOf(10);,所以a和b得到都是一个Cache对象,并且是同一个!而c和d是新创建的两个不同的对象,所以c自然不等于d。然而,当数据超出-128~127范围时,就不会先做Integer e = Integer.valueOf(200)这样的操作了。