Skip to content

Commit

Permalink
Improve performance of NumberUtils
Browse files Browse the repository at this point in the history
This commit aims to improve the space and time performance of
NumberUtils by invoking valueOf() factory methods instead of the
corresponding constructors when converting a number to a target class.
  • Loading branch information
sbrannen committed Aug 6, 2015
1 parent e0392d9 commit 48b965a
Showing 1 changed file with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,21 +91,21 @@ else if (Byte.class == targetClass) {
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Byte(number.byteValue());
return (T) Byte.valueOf(number.byteValue());
}
else if (Short.class == targetClass) {
long value = number.longValue();
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Short(number.shortValue());
return (T) Short.valueOf(number.shortValue());
}
else if (Integer.class == targetClass) {
long value = number.longValue();
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Integer(number.intValue());
return (T) Integer.valueOf(number.intValue());
}
else if (Long.class == targetClass) {
BigInteger bigInt = null;
Expand All @@ -119,7 +119,7 @@ else if (number instanceof BigDecimal) {
if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) {
raiseOverflowException(number, targetClass);
}
return (T) new Long(number.longValue());
return (T) Long.valueOf(number.longValue());
}
else if (BigInteger.class == targetClass) {
if (number instanceof BigDecimal) {
Expand All @@ -132,10 +132,10 @@ else if (BigInteger.class == targetClass) {
}
}
else if (Float.class == targetClass) {
return (T) new Float(number.floatValue());
return (T) Float.valueOf(number.floatValue());
}
else if (Double.class == targetClass) {
return (T) new Double(number.doubleValue());
return (T) Double.valueOf(number.doubleValue());
}
else if (BigDecimal.class == targetClass) {
// always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double)
Expand Down

0 comments on commit 48b965a

Please sign in to comment.