简体   繁体   中英

What is the most efficent way to print arrays in golang

I'm new to programming and wanted know more about the built-in functions:

Here is the is the program:

func main() {
    start := time.Now()

    fmt.Println(os.Args)

    fmt.Println(time.Since(start))
}

And its output:

[AB C DEFGHIJKLMNOP] 124.009µs

Here is my for loop:

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

}

with the following output:

/tmp/go-build994847456/b001/exe/main AB C DEFGHIJKLMNOP 25.71µs

I was expecting to have the built in function in the standard library to be faster.

Do slices make my code less efficient?

Should I use for loops or standard library fmt.println ?

I'm also confused how would the strings.Join(os.Args\[1:\], " ") performed 74.293µs

Use benchmarks:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM