...
1
2
3
4
5
6
7 package intern
8
9 import (
10 "bytes"
11 "reflect"
12 "testing"
13 "unsafe"
14 )
15
16 func TestString(t *testing.T) {
17 s := "abcde"
18 sub := String(s[1:4])
19 interned := String("bcd")
20 want := (*reflect.StringHeader)(unsafe.Pointer(&sub)).Data
21 got := (*reflect.StringHeader)(unsafe.Pointer(&interned)).Data
22 if want != got {
23 t.Errorf("failed to intern string")
24 }
25 }
26
27 func TestBytes(t *testing.T) {
28 s := bytes.Repeat([]byte("abc"), 100)
29 n := testing.AllocsPerRun(100, func() {
30 for i := 0; i < 100; i++ {
31 _ = Bytes(s[i*len("abc") : (i+1)*len("abc")])
32 }
33 })
34 if n > 0 {
35 t.Errorf("Bytes allocated %d, want 0", int(n))
36 }
37 }
38
39 func BenchmarkString(b *testing.B) {
40 in := "hello brad"
41 b.ReportAllocs()
42 b.SetBytes(int64(len(in)))
43 b.RunParallel(func(pb *testing.PB) {
44 var s string
45 for pb.Next() {
46 s = String(in[1:5])
47 }
48 _ = s
49 })
50 }
51
52 func BenchmarkBytes(b *testing.B) {
53 in := []byte("hello brad")
54 b.ReportAllocs()
55 b.SetBytes(int64(len(in)))
56 b.RunParallel(func(pb *testing.PB) {
57 var s string
58 for pb.Next() {
59 s = Bytes(in[1:5])
60 }
61 _ = s
62 })
63 }
64
View as plain text