I have a Java application that uses the compareTo()
method of the BigDecimal
class in order to classify a (big) real number, read as a string, according to its type (basically, "too big", double or float). The application reads a very large number of such strings per second, so any performance optimization is essential.
Following is an abbreviated excerpt of the code:
static final BigDecimal MAX_LONG = new BigDecimal(Long.MAX_VALUE);
static final BigDecimal MAX_FLOAT = new BigDecimal(Float.MAX_VALUE);
static final BigDecimal MAX_DOUBLE = new BigDecimal(Double.MAX_VALUE);
String value = readValue(); // Read the number as a string
BigDecimal number = new BigDecimal(value);
if (number.compareTo(MAX_DOUBLE) > 0)
{
...
}
else if (number.compareTo(MAX_FLOAT) > 0)
{
...
}
else if (number.compareTo(MAX_LONG) > 0)
{
...
}
So, 2 questions
As BigDecimal is immutable it is also therefore thread-safe.
You should also use BigDecimal.valueOf()
instead of new BigDecimal()
throughout, to take advantage of any caching that may be possible.