gh-129275: avoid temporary buffer in dec_as_long() by skirpichev · Pull Request #129630 · python/cpython
According to the documentation: "If rdata is non-NULL, it MUST be allocated by one of libmpdec’s allocation functions and rlen MUST be correct. If necessary, the function will resize rdata. Resizing is slow and should not occur if rlen has been obtained by a call to mpd_sizeinbase."
So, possible resizing in mpd_qexport_u32/16() is for guarding against broken log10() implementations (log10 is used in the mpd_sizeinbase()).
Temporary memory allocation slowdown conversion for small integers (~2 digits):
| Benchmark | ref | patch |
|---|---|---|
| int(Decimal(1<<7)) | 499 ns | 495 ns: 1.01x faster |
| int(Decimal(1<<300)) | 2.16 us | 2.06 us: 1.05x faster |
| Geometric mean | (ref) | 1.02x faster |
Benchmark hidden because not significant (2): int(Decimal(1<<38)), int(Decimal(1<<3000))
Details
# bench_Decimal-to-int.py import pyperf from decimal import Decimal values = ['1<<7', '1<<38', '1<<300', '1<<3000'] runner = pyperf.Runner() for v in values: d = Decimal(eval(v)) bn = 'int(Decimal('+v+'))' runner.bench_func(bn, int, d)