How udecimal achieves high performance and zero allocation
masterThe Decimal type is a fixed-point representation consisting of a sign (neg), a coefficient (coef), and a precision (prec).
To minimize memory allocation, the coefficient coef uses a custom bint type:
- For coefficients that fit within a 128-bit unsigned integer (
u128), arithmetic is performed usingu128operations, which are extremely fast and require zero memory allocation. - If a result exceeds the
u128capacity, the library falls back to thebig.IntAPI. While this involves memory allocation and is slower, the 128-bit range is large enough that these cases are rare in most financial applications.
Precision Limits:
- Supports up to 19 decimal places.
- With precision 0, it can store values up to approximately $\pm 340$ undecillion.
- With precision 19, it can store values up to approximately $\pm 34$ quintillion.