Maison  >  Article  >  développement back-end  >  Quel est le moyen le plus efficace d'imprimer un tableau dans Golang

Quel est le moyen le plus efficace d'imprimer un tableau dans Golang

王林
王林avant
2024-02-10 09:30:23640parcourir

Quel est le moyen le plus efficace dimprimer un tableau dans Golang

Dans Golang, le moyen le plus efficace d'imprimer un tableau est d'utiliser la fonction Println dans le package fmt. En passant un tableau en paramètre à la fonction Println, elle formate et imprime automatiquement le contenu du tableau. Cette méthode est très simple et efficace et fonctionne pour n’importe quelle taille de tableau. De plus, Golang fournit également d'autres méthodes pour imprimer des tableaux, telles que l'utilisation de la fonction Join dans le package strings pour connecter les éléments du tableau en chaînes, puis les imprimer, ou l'utilisation d'une boucle pour parcourir le tableau et imprimer chaque élément. Mais relativement parlant, utiliser directement la fonction Println est la méthode la plus simple et la plus efficace. Que ce soit lors du développement ou du débogage, l'impression de tableaux est une opération très courante. Maîtriser la méthode la plus efficace peut améliorer l'efficacité du développement.

Contenu de la question

Je suis nouveau dans la programmation et je souhaite en savoir plus sur les fonctions intégrées :

Voici le programme :

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

    fmt.println(os.args)

    fmt.println(time.since(start))
}

et sa sortie :

[a b c d e f g h i j k l m n o p] 124.009µs

Voici ma boucle 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))

}

Le résultat est le suivant :

/tmp/go-build994847456/b001/exe/main a b c d e f g h i j k l m n o p 25.71μs

J'aurais aimé que les fonctions intégrées dans la bibliothèque standard soient plus rapides.

Le découpage rendra-t-il mon code moins efficace ?

Dois-je utiliser une boucle for ou la bibliothèque standardfmt.println ?

Je suis également confus strings.join(os.args[1:], " ") Comment effectuer 74,293μs

Solution

Utiliser le benchmark :

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer