作者kdok123 (小天)
看板java
标题[问题] Integer小於一个byte的问题
时间Mon Dec 22 20:05:22 2014
public static Integer valueOf(int i) {
return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}
/**
* A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
*/
private static final Integer[] SMALL_VALUES = new Integer[256];
static {
for (int i = -128; i < 128; i++) {
SMALL_VALUES[i + 128] = new Integer(i);
}
}
以上是我跑进去Integer里面看的valueOf的code
这边有个特性是假设宣告的变数小於一个byte
会直接指向static初始化new好的矩阵,否则重新new一个
我的疑问是:
就上面的例子来看,在run Integer.java的时候
会先new 255次来创造SMALL_VALUES array
这样做会比较有效率吗? 为什麽java选择这样做呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 60.250.185.98
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/java/M.1419249924.A.3F1.html
1F:→ cha122977: 这是要省记忆体(共用instance) 255次的cost期实很小 12/22 20:34
2F:→ ssccg: boxing的cost大,所以常用的值先产生好让所有人共用 12/22 22:18