PNS
PNS

Reputation: 19905

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?

Upvotes: 3

Views: 2010

Answers (3)

DuncanKinnear
DuncanKinnear

Reputation: 4643

If there are lots of numbers that are likely to be the same, then maybe a HashMap<String, BigDecimal> 'cache' of BigDecimal values might be faster.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533750

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?

Upvotes: 4

bluesman
bluesman

Reputation: 2260

I would agree that difference is unlikely to matter, however I would use valueOf as future versions of java are likely going to cache a lot of the common numbers.

Upvotes: 1

Related Questions