Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal constructor performance - string vs numeric

new BigDecimal("10000");
new BigDecimal(10000);

I know the string constructor is used if the number is bigger than the compiler would accept, but are either of the constructors faster than the other?

like image 480
MCMastery Avatar asked Jul 31 '26 02:07

MCMastery


2 Answers

You can look at source code.

public BigDecimal(int val) {
    intCompact = val;
}

public BigDecimal(String val) {
    this(val.toCharArray(), 0, val.length());
}

public BigDecimal(char[] in, int offset, int len) {
       ...very long
}

Obviously, who is faster.

like image 194
Zephyr Guo Avatar answered Aug 02 '26 15:08

Zephyr Guo


Passing a String to the constructor of BigDecimal requires a parsing of the String and a check char by char.

Passing an int is faster because it results only in a single assignment.

In any case the time difference is not signifiant.

Here the code of BigDecimal with an int parameter:

public BigDecimal(int val) {
    intCompact = val;
}

The code of BigDecimal constructor with a String calls BigDecimal(char[], int, int) that has around 140 rows of code.

like image 42
Davide Lorenzo MARINO Avatar answered Aug 02 '26 17:08

Davide Lorenzo MARINO