
[英]What is the most effective way to lock down external dependency “versions” in Golang?
[英]What is the most efficent way to print arrays in golang
我是编程新手,想了解更多关于内置函数的信息:
这是程序:
func main() {
start := time.Now()
fmt.Println(os.Args)
fmt.Println(time.Since(start))
}
及其 output:
[AB C DEFGHIJKLMNOP] 124.009µs
这是我的 for 循环:
package main
import (
"fmt"
"os"
"time"
)
func main() {
start := time.Now()
var s string
for i:=0; i<len(os.Args); i++{
s += os.Args[i] + " "
}
fmt.Println(s)
fmt.Println(time.Since(start))
}
使用以下 output:
/tmp/go-build994847456/b001/exe/main AB C DEFGHIJKLMNOP 25.71µs
我期望标准库中内置的 function 会更快。
切片会使我的代码效率降低吗?
我应该使用 for 循环还是标准库fmt.println
?
我也很困惑strings.Join(os.Args\[1:\], " ")
将如何执行 74.293µs
使用基准:
var slice = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"}
func BenchmarkFMT(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
_ = fmt.Sprint(slice)
}
}
func BenchmarkStringConcat(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
var str string
for _, s := range slice {
str += s + " "
}
}
}
func BenchmarkStringsBuilder(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
var l int
for _, s := range slice {
l += len(s)
}
var sb strings.Builder
sb.Grow(l + len(slice)*len(" "))
for _, s := range slice {
sb.WriteString(s)
sb.WriteString(" ")
}
_ = sb.String()
}
}
func BenchmarkStringsJoin(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
_ = strings.Join(slice, " ")
}
}
BenchmarkFMT
BenchmarkFMT-8 734088 1633 ns/op 616 B/op 34 allocs/op
BenchmarkStringConcat
BenchmarkStringConcat-8 1290666 919.1 ns/op 1200 B/op 32 allocs/op
BenchmarkStringsBuilder
BenchmarkStringsBuilder-8 6074888 198.6 ns/op 64 B/op 1 allocs/op
BenchmarkStringsJoin
BenchmarkStringsJoin-8 4941542 241.7 ns/op 64 B/op 1 allocs/op
PASS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.