
등등..
소스코드: https://github.com/yoon1/wil/tree/main/zero-allocation

이 포스트에서는 benchmark로 확인했음.
func withoutZeroAllocation() {
var slice []int
for i := 0; i < 1000000; i++ {
slice = append(slice, i)
}
}
func withZeroAllocation() {
array := [1000000]int{}
for i := 0; i < 1000000; i++ {
array[i] = i
}
}
func BenchmarkWithoutZeroAllocation(b *testing.B) {
for i := 0; i < b.N; i++ {
withoutZeroAllocation()
}
}
func BenchmarkWithZeroAllocation(b *testing.B) {
for i := 0; i < b.N; i++ {
withZeroAllocation()
}
}
go test -bench . -benchmem
BenchmarkWithoutZeroAllocation-10 3829 313277 ns/op 0 B/op 0 allocs/op
BenchmarkWithZeroAllocation-10 436 2709576 ns/op 41678186 B/op 39 allocs/op
func withoutZeroAllocationStr() string {
var s string
for n := 0; n < 1000000; n++ {
s += "Hello"
s += "World"
}
return s
}
func withZeroAllocationStr() string {
var builder strings.Builder
for n := 0; n < 1000000; n++ {
builder.WriteString("Hello")
builder.WriteString("World")
}
return builder.String()
}
benchmark code 및 실행 방법 위와 동일
BenchmarkWithZeroAllocationStr-10 15054 77785 ns/op 514810 B/op 24 allocs/op
BenchmarkWithoutZeroAllocationStr-10 16 70046294 ns/op 1061959346 B/op 20043 allocs/op
