Created
February 20, 2024 01:38
-
-
Save x1unix/1c2b6b89360ec148393b80fe10e83696 to your computer and use it in GitHub Desktop.
[GO] Append vs Copy
This file contains 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 main | |
import ( | |
"fmt" | |
"runtime" | |
"testing" | |
) | |
func BenchmarkAppend(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
i1 := []int{1, 2, 3} | |
i2 := []int{4, 5, 6} | |
o := make([]int, 0, len(i1)+len(i2)) | |
o = append(o, i1...) | |
o = append(o, i2...) | |
} | |
b.ReportAllocs() | |
} | |
func BenchmarkCopy(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
i1 := []int{1, 2, 3} | |
i2 := []int{4, 5, 6} | |
o := make([]int, len(i1)+len(i2)) | |
copy(o, i1) | |
copy(o[:len(i1)], i2) | |
} | |
b.ReportAllocs() | |
} | |
func main() { | |
bench("copy", BenchmarkCopy) | |
bench("append", BenchmarkAppend) | |
} | |
func bench(label string, fn func(b *testing.B)) { | |
fmt.Printf("=== Running %q ===\n", label) | |
var ( | |
startAllocs runtime.MemStats | |
endAllocs runtime.MemStats | |
) | |
runtime.ReadMemStats(&startAllocs) | |
res := testing.Benchmark(fn) | |
fmt.Println(res) | |
runtime.ReadMemStats(&endAllocs) | |
fmt.Printf("> Allocs: %d\n", endAllocs.Mallocs-startAllocs.Mallocs) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment