1
2
3
4
5 package test
6
7 import (
8 "internal/testenv"
9 "testing"
10 "unsafe"
11 )
12
13
14
15 const maxStackSize = 32
16
17
18 func genericUse[T any](s []T) {
19
20 }
21
22 func TestStackAllocation(t *testing.T) {
23 testenv.SkipIfOptimizationOff(t)
24
25 type testCase struct {
26 f func(int)
27 elemSize uintptr
28 }
29
30 for _, tc := range []testCase{
31 {
32 f: func(n int) {
33 genericUse(make([]int, n))
34 },
35 elemSize: unsafe.Sizeof(int(0)),
36 },
37 {
38 f: func(n int) {
39 genericUse(make([]*byte, n))
40 },
41 elemSize: unsafe.Sizeof((*byte)(nil)),
42 },
43 {
44 f: func(n int) {
45 genericUse(make([]string, n))
46 },
47 elemSize: unsafe.Sizeof(""),
48 },
49 } {
50 max := maxStackSize / int(tc.elemSize)
51 if n := testing.AllocsPerRun(10, func() {
52 tc.f(max)
53 }); n != 0 {
54 t.Fatalf("unexpected allocation: %f", n)
55 }
56 if n := testing.AllocsPerRun(10, func() {
57 tc.f(max + 1)
58 }); n != 1 {
59 t.Fatalf("unexpected allocation: %f", n)
60 }
61 }
62 }
63
View as plain text