为什么传递可变参数的速度如此之慢?

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)

为什么传递可变参数的速度如此之慢?

小智 5

最后一个 for 循环使用append 将较大的“dst3”切片多次添加到“dst1”切片中。它需要更多的时间,因为每次迭代都涉及将整个“dst3”切片复制到“dst1”切片。