]> Cypherpunks repositories - gostls13.git/commit
math/big: improve performance of Binomial
authorRiccardo Gerosa <riccardo.gerosa@nozominetworks.com>
Mon, 24 Oct 2022 22:41:02 +0000 (22:41 +0000)
committerRobert Griesemer <gri@google.com>
Fri, 28 Oct 2022 23:50:33 +0000 (23:50 +0000)
commit91a1f0d918f54e3b3425248288085db4d5619075
treef7f6f271f01abb62bbab3a89d53d655e90e58e71
parentb726b0cadb5102bb718f879bede0e76d1e5f5c34
math/big: improve performance of Binomial

This change improves the performance of Binomial by implementing an
algorithm that produces smaller intermediate values at each step.

Working with smaller big.Int values has the advantage that  fewer allocations
and computations are required for each mathematical operation.

The algorithm used is the Multiplicative Formula, which is a well known
way of calculating the Binomial coefficient and is described at:
https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
https://en.wikipedia.org/wiki/Binomial_coefficient#In_programming_languages

In addition to that, an optimization has been made to remove a
redundant computation of (i+1) on each loop which has a measurable
impact when using big.Int.

Performance improvement measured on an M1 MacBook Pro
running the existing benchmark for Binomial:

name        old time/op    new time/op    delta
Binomial-8     589ns ± 0%     435ns ± 0%  -26.05%  (p=0.000 n=10+10)

name        old alloc/op   new alloc/op   delta
Binomial-8    1.02kB ± 0%    0.08kB ± 0%  -92.19%  (p=0.000 n=10+10)

name        old allocs/op  new allocs/op  delta
Binomial-8      38.0 ± 0%       5.0 ± 0%  -86.84%  (p=0.000 n=10+10)

Change-Id: I5a830386dd42f062e17af88411dd74fcb110ded9
GitHub-Last-Rev: 6b2fca07de4096accb02f66c313dff47c2303462
GitHub-Pull-Request: golang/go#56339
Reviewed-on: https://go-review.googlesource.com/c/go/+/444315
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Run-TryBot: Robert Griesemer <gri@google.com>
src/math/big/int.go