Skip to content

Commit

Permalink
alg/heuristic: preallocate in Approximation (#107)
Browse files Browse the repository at this point in the history
The Approximation.Suggest() method is prominent in the allocation profile.
This PR reduces allocations by hoisting them out of the loop.

Updates #60
Updates #25
  • Loading branch information
mmcloughlin committed May 13, 2021
1 parent 05190c7 commit 035ef76
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions alg/heuristic/heuristic.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,10 @@ func (Approximation) String() string { return "approximation" }
// "small" positive value.
func (Approximation) Suggest(f []*big.Int, target *big.Int) []*big.Int {
delta := new(big.Int)
var mindelta *big.Int
var best *big.Int
insert := new(big.Int)
mindelta := new(big.Int)
best := new(big.Int)
first := true

// Leverage the fact that f contains sorted distinct integers to apply a
// linear algorithm, similar to the 2-SUM problem. Maintain left and right
Expand All @@ -146,17 +148,18 @@ func (Approximation) Suggest(f []*big.Int, target *big.Int) []*big.Int {
}

// Proposed insertion is a+delta.
insert := new(big.Int).Add(a, delta)
insert.Add(a, delta)

// If it's actually in the sequence already, use it.
if bigints.ContainsSorted(insert, f) {
return []*big.Int{insert}
}

// Keep it if its the closest we've seen.
if best == nil || delta.Cmp(mindelta) < 0 {
mindelta = bigint.Clone(delta)
best = insert
if first || delta.Cmp(mindelta) < 0 {
mindelta.Set(delta)
best.Set(insert)
first = false
}

// Advance to next a value.
Expand Down

0 comments on commit 035ef76

Please sign in to comment.