Consider an application that
String
values from a text file.String
value representing a number, instantiates a BigDecimal
object (at a total rate of thousands of Bigdecimal objects per second).BigDecimal
object for further processing.Given the above scenario, obviously the instantiation of each BigDecimal
object has an impact on performance.
One way to instantiate those BigDecimal
objects from a non-null String str
, is:
BigDecimal number = new BigDecimal(str.toCharArray(), 0, str.length()));
which is exactly what the String constructor of BigDecimal expands to in the Oracle
implementation of the JDK
.
Is there a faster way of instantiating BigDecimal
objects from such strings, or via an alternative approach?
I would use
BigDecimal number = new BigDecimal(str);
which is simpler and the difference is unlikely to matter.
If you need performance and you don't need more than 15 digits of accuracy you can use double
instead.
You need to performance I would look at the performance of your whole application before micro-optimising. You mention using a regular expression and this can use more CPU than creating strings or BigDecimal. Can you profile your application?