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

huangapple go评论74阅读模式
英文:

Why is it so badly slow to pass variadic arguments?

问题

以下是代码的中文翻译:

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()))
}

基准测试结果:

2
2
2711

为什么传递可变参数会如此慢?

英文:
package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

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 &lt; n; i++ {
		dst1[i] = byte(i)
	}
	fmt.Println(uint64(time.Since(start).Microseconds()))

	start = time.Now()
	for i := 0; i &lt; n; i++ {
		dst2 = append(dst2, dst1[i])
	}
	fmt.Println(uint64(time.Since(start).Microseconds()))

	start = time.Now()
	for i := 0; i &lt; 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

得分: 5

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

英文:

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.

huangapple
  • 本文由 发表于 2023年7月2日 12:48:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76597432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定