xml*_*lmx -2 performance idioms parameter-passing variadic-functions go
package main
import (
"fmt"
"time"
)
func main() {
n := 1024
dst1 := make([]byte, n)
dst2 := make([]byte, 0, n)
dst3 := make([]byte, 0, n)
start := time.Now()
for i := 0; i < n; i++ {
dst1[i] = byte(i)
}
fmt.Println(uint64(time.Since(start).Microseconds()))
start = time.Now()
for i := 0; i < n; i++ {
dst2 = append(dst2, dst1[i])
}
fmt.Println(uint64(time.Since(start).Microseconds()))
start = time.Now()
for i := 0; i < n; i++ {
dst3 = append(dst3, dst1...)
}
fmt.Println(uint64(time.Since(start).Microseconds()))
}
Run Code Online (Sandbox Code Playgroud)
基准测试结果:
2
2
2711
Run Code Online (Sandbox Code Playgroud)
为什么传递可变参数的速度如此之慢?