Last active
May 10, 2019 06:03
-
-
Save bingoohuang/e1f5de5d404c56096ebfc2652df22fc7 to your computer and use it in GitHub Desktop.
compare two style of copy golang slice performance
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 gotrial | |
import ( | |
"strings" | |
"testing" | |
) | |
func copyListV1(in []string) []string { | |
var out []string | |
for _, s := range in { | |
out = append(out, s) | |
} | |
return out | |
} | |
func copyListV2(in []string) []string { | |
out := make([]string, len(in)) | |
for i, s := range in { | |
out[i] = s | |
} | |
return out | |
} | |
var input = strings.Fields(`Making code faster is exciting, and benchmarks in Go make that easy to do! Not really. | |
Optimizing a program can be complex and require careful consideration to do properly. | |
Daniel demonstrates techniques and tools which are a must for any performance aficionado.`) | |
func BenchmarkCopyList(b *testing.B) { | |
b.ReportAllocs() | |
for i := 0; i < b.N; i++ { | |
copyListV2(input) | |
} | |
} |
Author
bingoohuang
commented
May 10, 2019
➜ gotrial go get golang.org/x/perf/cmd/benchstat
➜ gotrial benchstat v1.txt v2.txt
name old time/op new time/op delta
CopyList-12 703ns ± 0% 190ns ± 0% ~ (p=1.000 n=1+1)
name old alloc/op new alloc/op delta
CopyList-12 2.03kB ± 0% 0.70kB ± 0% ~ (p=1.000 n=1+1)
name old allocs/op new allocs/op delta
CopyList-12 7.00 ± 0% 1.00 ± 0% ~ (p=1.000 n=1+1)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment