Why is it so badly slow to pass variadic arguments?

121 Views Asked by At
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()))
}

The benchmark results:

2
2  
2711

Why is it so badly slow to pass variadic arguments?

1

There are 1 best solutions below

1
NubDev On BEST ANSWER

The last for loop uses append to add the larger "dst3" slice to the "dst1" slice multiple times. It takes significantly more time because each iteration involves copying the entire "dst3" slice to the "dst1" slice.