Files
bulma/gc_slice_prealloc.go

44 lines
906 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"runtime"
"time"
)
// noPrealloc 未预分配容量,频繁扩容
func noPrealloc() {
var data []int
for i := 0; i < 100000; i++ {
data = append(data, i)
}
}
// withPrealloc 预分配容量,无扩容
func withPrealloc() {
data := make([]int, 0, 100000) // 预分配容量100000
for i := 0; i < 100000; i++ {
data = append(data, i)
}
}
func main() {
var stats runtime.MemStats
// 测试未预分配
runtime.GC()
start := time.Now()
noPrealloc()
dur1 := time.Since(start)
runtime.ReadMemStats(&stats)
fmt.Printf("未预分配:耗时%v,堆分配%d KBGC次数%d\n", dur1, stats.HeapAlloc/1024, stats.NumGC)
// 测试预分配
runtime.GC()
start = time.Now()
withPrealloc()
dur2 := time.Since(start)
runtime.ReadMemStats(&stats)
fmt.Printf("预分配:耗时%v,堆分配%d KBGC次数%d\n", dur2, stats.HeapAlloc/1024, stats.NumGC)
}