Luuk van Dijk | d6b2925 | 2011-05-11 16:35:11 +0200 | [diff] [blame] | 1 | // 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. |
| 4 | package runtime_test |
| 5 | |
| 6 | import "testing" |
| 7 | |
| 8 | const N = 20 |
| 9 | |
| 10 | func 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 | |
| 22 | func 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 Cox | 29125be | 2011-07-14 23:43:03 -0400 | [diff] [blame] | 39 | var x []int |
Luuk van Dijk | d6b2925 | 2011-05-11 16:35:11 +0200 | [diff] [blame] | 40 | |
| 41 | func f() int { |
| 42 | x[:1][0] = 3 |
| 43 | return 2 |
| 44 | } |
| 45 | |
| 46 | func TestSideEffectOrder(t *testing.T) { |
Russ Cox | 29125be | 2011-07-14 23:43:03 -0400 | [diff] [blame] | 47 | x = make([]int, 0, 10) |
Luuk van Dijk | d6b2925 | 2011-05-11 16:35:11 +0200 | [diff] [blame] | 48 | x = append(x, 1, f()) |
| 49 | if x[0] != 1 || x[1] != 2 { |
| 50 | t.Error("append failed: ", x[0], x[1]) |
| 51 | } |
| 52 | } |