当你把Findbugs集成到Jenkins之后,你很快会爱上它。因为现在多了一双眼睛帮你检查代码质量。
当Findbugs发现你的代码里有这样的Code,
1 2 |
... new Integer(a.getSomeValue()).compareTo(anotherInt); |
Findbugs就会报警了,它会提醒你用Integer.valueOf()来取代new Integer(),说会有更高的效率。为什么呢?原因其实很简单。看下面的代码,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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) { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low)); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} } |
Java从IntegerCache.low到IntegerCache.high的整数做了Cache,在类加载时,就事先把对像创建好,节省对小整数的分配开销。
IntegerCache.high默认是127,但我们也可以把这个数提高,比如在运行java程序时,加上-Djava.lang.Integer.IntegerCache.high=1024。那high现在就是1024了。
这种Cache机制也会有点Confusing的地方,比如下面的代码,
1 2 3 4 5 6 7 8 9 |
Integer i = new Integer(127); Integer j = new Integer(127); System.out.println(i == j); // <strong>false</strong> i = Integer.valueOf(127); j = Integer.valueOf(127); System.out.println(i == j); // <strong>true</strong> |
搞清了原理,大家就看情况使用吧!