英文:
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 (
"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
得分: 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论