Permalink
Browse files

Speed up array operations

Two tweaks to evalIndex: one is to simply speed up the common case
of a 1-dimensional index and avoid the loop entirely. The other is
to allocate an array of fixed size (3) to begin with so the compiler
can do that first allocation on the heap.

ArrayOperations-8       1.80µs ± 1%  1.13µs ± 1%  -37.52%  (p=0.008 n=5+5)
  • Loading branch information...
benhoyt committed Sep 7, 2018
1 parent 2082073 commit af993094e3e8aca2b7ab709ffcda437996c906fe
Showing with 13 additions and 3 deletions.
  1. +13 −3 interp/interp.go
@@ -1745,13 +1745,23 @@ func (p *interp) assign(left Expr, right value) error {
}

func (p *interp) evalIndex(indexExprs []Expr) (string, error) {
indices := make([]string, len(indexExprs))
for i, expr := range indexExprs {
// Optimize the common case of a 1-dimensional index
if len(indexExprs) == 1 {
v, err := p.eval(indexExprs[0])
if err != nil {
return "", err
}
return p.toString(v), nil
}

// Up to 3-dimensional indices won't require heap allocation
indices := make([]string, 0, 3)
for _, expr := range indexExprs {
v, err := p.eval(expr)
if err != nil {
return "", err
}
indices[i] = p.toString(v)
indices = append(indices, p.toString(v))
}
return strings.Join(indices, p.subscriptSep), nil
}

0 comments on commit af99309

Please sign in to comment.