From 8ad895b51b878296e1e538f1602469d13227ab46 Mon Sep 17 00:00:00 2001 From: Dan Kortschak Date: Sun, 16 Feb 2020 15:45:16 +1030 Subject: [PATCH] optimize: avoid unnecessary allocations for Gradient and Hessian --- optimize/minimize.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/optimize/minimize.go b/optimize/minimize.go index 17c3675a..94cf8f8b 100644 --- a/optimize/minimize.go +++ b/optimize/minimize.go @@ -478,19 +478,22 @@ func evaluate(p *Problem, loc *Location, op Operation, x []float64) { } if op&GradEvaluation != 0 { // Make sure we have a destination in which to place the gradient. - // TODO(kortschak): Consider making this a check of len(loc.Gradient) != 0 - // to allow reuse of the slice. - if loc.Gradient == nil { - loc.Gradient = make([]float64, len(x)) + if len(loc.Gradient) == 0 { + if cap(loc.Gradient) < len(x) { + loc.Gradient = make([]float64, len(x)) + } else { + loc.Gradient = loc.Gradient[:len(x)] + } } p.Grad(loc.Gradient, x) } if op&HessEvaluation != 0 { // Make sure we have a destination in which to place the Hessian. - // TODO(kortschak): Consider making this a check of loc.Hessian.IsZero() - // to allow reuse of the matrix. - if loc.Hessian == nil { + switch { + case loc.Hessian == nil: loc.Hessian = mat.NewSymDense(len(x), nil) + case loc.Hessian.IsEmpty(): + loc.Hessian.ReuseAsSym(len(x)) } p.Hess(loc.Hessian, x) }