1
0
mirror of https://github.com/golang/go synced 2024-11-23 14:20:05 -07:00
go/test/fixedbugs/issue5373.go
Josh Bleecher Snyder f03c9202c4 cmd/gc: optimize memclr of slices and arrays
Recognize loops of the form

for i := range a {
	a[i] = zero
}

in which the evaluation of a is free from side effects.
Replace these loops with calls to memclr.
This occurs in the stdlib in 18 places.

The motivating example is clearing a byte slice:

benchmark                old ns/op     new ns/op     delta
BenchmarkGoMemclr5       3.31          3.26          -1.51%
BenchmarkGoMemclr16      13.7          3.28          -76.06%
BenchmarkGoMemclr64      50.8          4.14          -91.85%
BenchmarkGoMemclr256     157           6.02          -96.17%

Update #5373.

Change-Id: I99d3e6f5f268e8c6499b7e661df46403e5eb83e4
Reviewed-on: https://go-review.googlesource.com/2520
Reviewed-by: Keith Randall <khr@golang.org>
2015-01-09 22:35:25 +00:00

72 lines
1.4 KiB
Go

// run
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Ensure that zeroing range loops have the requisite side-effects.
package main
import (
"fmt"
"os"
)
func check(n int) {
// When n == 0, i is untouched by the range loop.
// Picking an initial value of -1 for i makes the
// "want" calculation below correct in all cases.
i := -1
s := make([]byte, n)
for i = range s {
s[i] = 0
}
if want := n - 1; i != want {
fmt.Printf("index after range with side-effect = %d want %d\n", i, want)
os.Exit(1)
}
i = n + 1
// i is shadowed here, so its value should be unchanged.
for i := range s {
s[i] = 0
}
if want := n + 1; i != want {
fmt.Printf("index after range without side-effect = %d want %d\n", i, want)
os.Exit(1)
}
// Index variable whose evaluation has side-effects
var x int
f := func() int {
x++
return 0
}
var a [1]int
for a[f()] = range s {
s[a[f()]] = 0
}
if want := n * 2; x != want {
fmt.Printf("index function calls = %d want %d\n", x, want)
os.Exit(1)
}
// Range expression whose evaluation has side-effects
x = 0
b := [1][]byte{s}
for i := range b[f()] {
b[f()][i] = 0
}
if want := n + 1; x != n+1 {
fmt.Printf("range expr function calls = %d want %d\n", x, want)
os.Exit(1)
}
}
func main() {
check(0)
check(1)
check(15)
}