Loading
Optimize GetUncappedShare with integer big.Int math (+ tests/benchmarks)
Summary
This MR replaces GetUncappedShare’s decimal-based implementation with an integer-only big.Int implementation, while keeping the old path as GetUncappedShareV1 for comparison/testing.
Motivation
The previous implementation used LegacyDec conversions and multiple decimal operations, which:
- added significant allocation/CPU overhead
- introduced intermediate precision/rounding behavior differences
The new implementation computes share directly in integer arithmetic with final round-half-up behavior.
Changes
- Added new fast path:
GetUncappedShare- integer formula:
(allocation*part + floor(total/2)) / total
- Kept prior behavior as:
GetUncappedShareV1(...)
- Added/updated tests:
- V1 vs V2 behavior checks
- overflow-safe large number coverage
- deterministic example case showing expected delta
- Added benchmarks for small and large input profiles.
- Updated affected mocknet test expectations where rounding output changed by small integer amounts.
Benchmark
Command:
go test ./common -run '^$' -bench '^Benchmark_GetUncappedShare_' -benchmem
Environment: linux, amd64, AMD Ryzen 9 8945HS
Raw results
| Benchmark | ns/op | B/op | allocs/op |
|---|---|---|---|
| V1 Small | 1450.0 | 1008 | 39 |
| V2 Small | 194.9 | 192 | 13 |
| V1 Large | 1669.0 | 1192 | 41 |
| V2 Large | 214.8 | 232 | 13 |
Ratio comparison (V1 vs V2)
| Category | Latency speedup | Memory reduction | Allocation reduction |
|---|---|---|---|
| Small | 7.44x faster (-86.6% ns/op) |
5.25x less (-81.0% B/op) |
3.00x less (-66.7% allocs/op) |
| Large | 7.77x faster (-87.1% ns/op) |
5.14x less (-80.5% B/op) |
3.15x less (-68.3% allocs/op) |
Notes
Behavior is deterministic but may differ by small integer amounts in edge rounding cases versus V1 Tests were updated accordingly.