Search code examples
javaperformanceinstantiationbigdecimal

Fastest way to instantiate BigDecimal from string


Consider an application that

  1. Reads several thousands of String values from a text file.
  2. Selects (via a regular expression match) those values that represent a number (from simple integers to very large values written in scientific notation with mantissa).
  3. For each String value representing a number, instantiates a BigDecimal object (at a total rate of thousands of Bigdecimal objects per second).
  4. Uses each instantiated 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?


Solution

  • 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?