なんとなくblogをめぐっていたら興味深いネタを見つけた。
今日のひとこと Integer.valueOf(int)
Integer.valueOf(int)は内部で-128から127までのIntegerをキャッシュしているらしい。
だからnew Integer(int)よりもパフォーマンスが向上するというお話。
GoFデザインパターンのFlyweightパターンが活きているわけだ。
なお、java.lang.Integer#valueOf(int)は以下のようなソースになっている。
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> 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.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
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);
}
投稿日時 : 2007年10月17日 13:56