Description
Bx: Method invokes inefficient new Integer(int) constructor; use Integer.valueOf(int) instead
Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.
Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.
Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.
使用new Integer(int)等於建立新的物件,若透過Integer.valueOf(int),先前有create過就會從cache中取得。
Solution
用Integer.valueOf(int)取代new Integer(int)
Example
Before:
currentFiles.put(theDirectory.getAbsolutePath(),new Long(theDirectory.lastModified()));
After:
currentFiles.put(theDirectory.getAbsolutePath(), Long.valueOf(theDirectory.lastModified()));
留言
張貼留言