-
Notifications
You must be signed in to change notification settings - Fork 1
/
magicstring_test.go
145 lines (121 loc) · 2.5 KB
/
magicstring_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// Copyright 2022 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package magicstring
import (
"runtime"
"testing"
"time"
"github.com/huandu/go-assert"
)
func TestGCSafety(t *testing.T) {
a := assert.New(t)
value := 123
iterateStrings(func(s string) {
data := &testStruct{
Foo: value,
}
copiedData := *data
attached := Attach(s, data)
dataChan := make(chan int, 1)
gcDone := make(chan bool, 1)
runtime.SetFinalizer(data, func(data *testStruct) {
dataChan <- data.Foo
gcDone <- true
})
data = nil // Don't keep reference to the data anymore.
for i := 0; i < 10; i++ {
time.Sleep(time.Millisecond)
runtime.GC()
}
// Decode must work as expected after a few GC calls.
payload := Read(attached)
a.Equal(payload, &copiedData)
payload = nil
// Clear attached string to release internal data.
attached = ""
for i := 0; i < 10; i++ {
time.Sleep(time.Millisecond)
runtime.GC()
}
// The original data must be finalized.
select {
case <-gcDone:
default:
a.Fatalf("The data must be finalized")
}
select {
case v := <-dataChan:
a.Equal(v, value)
default:
a.Fatalf("The value in the data must be set in finalizer")
}
})
}
func BenchmarkAttachSmallString(b *testing.B) {
s := "small"
data := map[string]int{
"foo": 123,
"bar": 345,
}
for i := 0; i < b.N; i++ {
Attach(s, data)
}
}
func BenchmarkAttachLarge1MBString(b *testing.B) {
s := makeString(1 * 1024 * 1024)
data := map[string]int{
"foo": 123,
"bar": 345,
}
for i := 0; i < b.N; i++ {
Attach(s, data)
}
}
func BenchmarkReplaceSmallString(b *testing.B) {
s := "small"
var data interface{} = map[string]int{
"foo": 123,
"bar": 345,
}
attached := Attach(s, nil)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Replace(attached, data)
}
}
func BenchmarkReplaceLarge1MBString(b *testing.B) {
s := makeString(1 * 1024 * 1024)
var data interface{} = map[string]int{
"foo": 123,
"bar": 345,
}
attached := Attach(s, nil)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Replace(attached, data)
}
}
func BenchmarkReadSmallString(b *testing.B) {
s1 := "small"
data := map[string]int{
"foo": 123,
"bar": 345,
}
s2 := Attach(s1, data)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Read(s2)
}
}
func BenchmarkReadLarge1MBString(b *testing.B) {
s1 := makeString(1 * 1024 * 1024)
data := map[string]int{
"foo": 123,
"bar": 345,
}
s2 := Attach(s1, data)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Read(s2)
}
}