這裡分類和彙總了欣宸的全部原創(含配套原始碼):https://github.com/zq2599/blog_demos
go test -bench='Fib$' -benchmem .
// 往切片中放入指定數量的亂數,這個切片沒有提前設定容量
func newSlice(n int) []int {
rand.Seed(time.Now().UnixNano())
// 注意,這裡在生成切片的時候並沒有指定容量
nums := make([]int, 0)
for i := 0; i < n; i++ {
nums = append(nums, rand.Int())
}
return nums
}
// 往切片中放入指定數量的亂數,這個切片提前設定了容量
func newSliceWithCap(n int) []int {
rand.Seed(time.Now().UnixNano())
// 注意,這裡在生成切片的時候指定了容量
nums := make([]int, 0, n)
for i := 0; i < n; i++ {
nums = append(nums, rand.Int())
}
return nums
}
const (
SLICE_LENGTH_MILLION = 1000000 // 往切片中新增資料的長度,百萬
SLICE_LENGTH_TEN_MILLION = 10000000 // 往切片中新增資料的長度,千萬
SLICE_LENGTH_HUNDRED_MILLION = 100000000 // 往切片中新增資料的長度,億
)
func BenchmarkNewSlice(b *testing.B) {
for n := 0; n < b.N; n++ {
newSlice(SLICE_LENGTH_MILLION)
}
}
func BenchmarkNewSliceWithCap(b *testing.B) {
for n := 0; n < b.N; n++ {
newSliceWithCap(SLICE_LENGTH_MILLION)
}
}
go test -bench='BenchmarkNewSlice$|BenchmarkNewSliceWithCap$' -benchmem .
go test -bench='BenchmarkNewSlice$|BenchmarkNewSliceWithCap$' -benchmem .
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkNewSlice-8 68 16568869 ns/op 41678153 B/op 38 allocs/op
BenchmarkNewSliceWithCap-8 84 14098503 ns/op 8003589 B/op 1 allocs/op
PASS
ok benchmark-demo 2.769s
func testNewSlice(len int, b *testing.B) {
for n := 0; n < b.N; n++ {
newSlice(len)
}
}
func BenchmarkNewSlicMillion(b *testing.B) {
testNewSlice(SLICE_LENGTH_MILLION, b)
}
func BenchmarkNewSlicTenMillion(b *testing.B) {
testNewSlice(SLICE_LENGTH_TEN_MILLION, b)
}
func BenchmarkNewSlicHundredMillion(b *testing.B) {
testNewSlice(SLICE_LENGTH_HUNDRED_MILLION, b)
}
go test -bench='Million$' -benchmem .
go test -bench='Million$' -benchmem .
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkNewSlicMillion-8 67 16283754 ns/op 41678145 B/op 38 allocs/op
BenchmarkNewSlicTenMillion-8 7 159938941 ns/op 492000525 B/op 49 allocs/op
BenchmarkNewSlicHundredMillion-8 1 2242365417 ns/op 4589008224 B/op 60 allocs/op