Created
October 30, 2020 19:39
-
-
Save chrisconley/616750cc0fa5d1c25b1962ad7a36661f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package simple | |
import ( | |
"reflect" | |
"runtime" | |
"testing" | |
) | |
func AssertDeepEqual(x, y interface{}, t *testing.T) { | |
if !reflect.DeepEqual(x, y) { | |
t.Errorf("\ngot %s\nexp %s", x, y) | |
} | |
} | |
type Widget struct { | |
data []byte | |
} | |
func BuildWidgets(builder func(d []byte) Widget) []Widget { | |
widgets := []Widget{} | |
for i := 1; i <= 10; i++ { | |
data := make([]byte, 100*1024*1024) | |
widget := builder(data) | |
widgets = append(widgets, widget) | |
// Force GC to attempt clean up of each widget | |
runtime.GC() | |
} | |
return widgets | |
} | |
func TestDirectSliceHoldsMemory(t *testing.T) { | |
rtm := runtime.MemStats{} | |
builder := func(data []byte) Widget { | |
return Widget{data: data[0:1]} | |
} | |
widgets := BuildWidgets(builder) | |
AssertDeepEqual(len(widgets), 10, t) | |
// Memory is still on heap | |
runtime.ReadMemStats(&rtm) | |
AssertDeepEqual(int(rtm.HeapInuse/1024/1024), 1000, t) | |
// Running GC at this point collects the memory | |
runtime.GC() | |
runtime.ReadMemStats(&rtm) | |
AssertDeepEqual(int(rtm.HeapInuse/1024/1024), 0, t) | |
} | |
func TestCopyReleasesMemory(t *testing.T) { | |
rtm := runtime.MemStats{} | |
builder := func(data []byte) Widget { | |
copiedData := make([]byte, 2) | |
copy(copiedData, data[0:1]) | |
return Widget{data: copiedData} | |
} | |
widgets := BuildWidgets(builder) | |
AssertDeepEqual(len(widgets), 10, t) | |
// Memory has already been collected | |
runtime.ReadMemStats(&rtm) | |
AssertDeepEqual(int(rtm.HeapInuse/1024/1024), 0, t) | |
} | |
func TestAppendReleasesMemory(t *testing.T) { | |
rtm := runtime.MemStats{} | |
builder := func(data []byte) Widget { | |
return Widget{data: append([]byte{}, data[0:1]...)} | |
} | |
widgets := BuildWidgets(builder) | |
AssertDeepEqual(len(widgets), 10, t) | |
// Memory has already been collected | |
runtime.ReadMemStats(&rtm) | |
AssertDeepEqual(int(rtm.HeapInuse/1024/1024), 0, t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment