看板 java 關於我們 聯絡資訊
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://www.ptt.cc/bbs/java/M.1419249924.A.3F1.html
cha122977: 這是要省記憶體(共用instance) 255次的cost期實很小 12/22 20:34
ssccg: boxing的cost大,所以常用的值先產生好讓所有人共用 12/22 22:18