简体   繁体   中英

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?

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?

我同意差异不太重要,但我会使用valueOf,因为未来版本的java可能会缓存很多常见数字。

如果有很多可能相同的数字,那么BigDecimal值的HashMap<String, BigDecimal> 'cache'可能会更快。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM