我知道在Java中,有以下三种不同的方法将原始类型转换为其相应的包装类。但是,如果性能至关重要,是否有任何首选方法?
Integer i = new Integer(5);
Integer i = 5;
Integer i = Integer.valueOf(5);
最佳答案
Integer.valueOf(int) 的 javadoc发出非常明确的建议:
If a new
Integer
instance is not required, this method should generally be used in preference to the constructorInteger(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
to127
, inclusive, and may cache other values outside of this range.
正如 Pshemo
在评论中所指出的,以及本 SO thread 中所考虑的那样,Integer i = 5;
本质上会自动转换为 Integer i = Integer.valueOf(5);
。因此,使用任何一个都不会在性能方面产生差异。
因此,如果性能是一个问题,只需避免使用 new Integer(5)
即可从缓存中受益。
关于java - 在 Java 中创建原始包装类的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801762/