Skip to content

Skip redundant buffer finalisation on heap add/sub - #68

Closed
DRMacIver wants to merge 2 commits into
cmpute:masterfrom
DRMacIver:opt/p3-from-buffer-normalized
Closed

Skip redundant buffer finalisation on heap add/sub#68
DRMacIver wants to merge 2 commits into
cmpute:masterfrom
DRMacIver:opt/p3-from-buffer-normalized

Conversation

@DRMacIver

@DRMacIver DRMacIver commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

When adding heap-allocated integers, we can often skip reshaping the final buffer when the result shape is already known from the operation, which saves some time.

This is probably a bit marginal to be worth it TBH. It looked bigger in my initial benchmarking, and when I fixed the benchmarking most of the wins went away. Up to you whether you want to keep this - it's in the region of a 1% improvement on some operations, but it's quite fiddly for that small gain.

Benchmarks (layout-sampled, K=11)

Wall-clock, dashu-only, vs the merge base, measured under 11 randomised function layouts (ld64 -order_file) and reported as the median — to average out the ±10% code-placement noise that otherwise swamps these small-value micro-benchmarks. The untouched ubig_mul control reads 0.0% ± 0.0%, confirming a clean run.

Modest but real on the heap add/sub path it targets; inline sizes and the mul/cmp controls are unchanged.

Benchmark Δ
ubig_sub 1000-bit −1.5%
ubig_add / ubig_sub 10000-bit −0.6%
ubig_add 1000-bit −1.5% (±2.2 layout)
ubig_mul (control) 0.0%

Repr::from_buffer does pop_zeros + shrink_to_fit + match-on-len. On the
in-place Add/Sub paths that start from a Large (heap) operand and stay
heap-resident, the result shape is known from the operation, so that
finalisation is redundant.

Add a Repr::from_buffer_normalized helper (asserts the canonical-heap
preconditions in debug, transmutes directly in release) and route the
heap-stay-heap add/sub helpers through it, falling back to full
from_buffer only where a borrow can zero the top word.

Adds test_not_ibig_large, which drives the heap +1/-1 helpers
(add_large_one / sub_large_one, reached via two's-complement `!` on
multi-word magnitudes) including the top-word-zeroing fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@DRMacIver
DRMacIver marked this pull request as ready for review June 2, 2026 09:04
@cmpute

cmpute commented Jun 3, 2026

Copy link
Copy Markdown
Owner

Thanks for proposing this, I think it's a little over optimized. The difference will be at the level of only one or two comparisons. Closing for now.

@cmpute cmpute closed this Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants