I heard that the BigDecimal.valueOf()
method is better than calling new BigDecimal()
because it caches common values. I wanted to know how the caching mechanism of valueOf
works.

- 31,598
- 14
- 77
- 90

- 75
- 5
-
does [this](http://azagorneanu.blogspot.in/2011/07/javamathbigdecimal-performance.html) help you – Ankur Singhal Jan 05 '15 at 08:55
-
1I found correct answer in another topic [correct answer](https://stackoverflow.com/a/8561795/6301562) – dawis11 Nov 22 '19 at 23:20
2 Answers
Looking at the JDK 1.8 sources, it looks like it's just a static array which is initialized as part of class initialization - it only caches the values 0 to 10 inclusive, but that's an implementation detail. For example, given dasblinkenlight's post, it looks like earlier versions only cached 0 and 1.
For more detail - and to make sure you're getting information about the JDK which you're actually running - look at the source of the JDK you're using for yourself - most IDEs will open the relevant source code automatically, if they detect the source archive has been included in your JDK installation. Of course, if you're using a different JRE at execution time, you'd need to validate that too.
It's easy to tell whether or not a value has been cached, based on reference equality. Here's a short but complete program which finds the first non-negative value which isn't cached:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
for (long x = 0; x < Long.MAX_VALUE; x++) {
if (BigDecimal.valueOf(x) != BigDecimal.valueOf(x)) {
System.out.println("Value for " + x + " wasn't cached");
break;
}
}
}
}
On my machine with Java 8, the output is:
Value for 11 wasn't cached
Of course, an implementation could always cache the most recently requested value, in which case the above code would run for a very long time and then finish with no output...

- 1,421,763
- 867
- 9,128
- 9,194
If I m not wrong it caches only zero,one, two and ten, Thats why we have only
public static final BigInteger ZERO = new BigInteger(new int[0], 0);
public static final BigInteger ONE = valueOf(1);
private static final BigInteger TWO = valueOf(2);
public static final BigInteger TEN = valueOf(10);
That also calls valueOf(x) method.

- 2,278
- 11
- 23
-
1Question about BigDecimal and BigDecimal cache from 0 to 10 also ZERO, ONE, TWO and TEN just constant in this class. I don't know why you answered about BigInteger. – dawis11 Nov 22 '19 at 23:22