blob: b8552224e5b881532439608958aa1bb64dc8a575 [file] [log] [blame]
Luuk van Dijkd6b29252011-05-11 16:35:11 +02001// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4package runtime_test
5
6import "testing"
7
8const N = 20
9
10func BenchmarkAppend(b *testing.B) {
11 b.StopTimer()
12 x := make([]int, 0, N)
13 b.StartTimer()
14 for i := 0; i < b.N; i++ {
15 x = x[0:0]
16 for j := 0; j < N; j++ {
17 x = append(x, j)
18 }
19 }
20}
21
22func BenchmarkAppendSpecialCase(b *testing.B) {
23 b.StopTimer()
24 x := make([]int, 0, N)
25 b.StartTimer()
26 for i := 0; i < b.N; i++ {
27 x = x[0:0]
28 for j := 0; j < N; j++ {
29 if len(x) < cap(x) {
30 x = x[:len(x)+1]
31 x[len(x)-1] = j
32 } else {
33 x = append(x, j)
34 }
35 }
36 }
37}
38
Russ Cox29125be2011-07-14 23:43:03 -040039var x []int
Luuk van Dijkd6b29252011-05-11 16:35:11 +020040
41func f() int {
42 x[:1][0] = 3
43 return 2
44}
45
46func TestSideEffectOrder(t *testing.T) {
Russ Cox29125be2011-07-14 23:43:03 -040047 x = make([]int, 0, 10)
Luuk van Dijkd6b29252011-05-11 16:35:11 +020048 x = append(x, 1, f())
49 if x[0] != 1 || x[1] != 2 {
50 t.Error("append failed: ", x[0], x[1])
51 }
52}