Benchmark: Splitting Command-Line Arguments by Golang

This sample script is for splitting command-line arguments by golang. There are 2 types. One is the regular expression is used. Another is that Split() and TrimSpace() are used.

Here, each process speed was compared.

Script :

package main

import (
    "regexp"
    "strings"
    "testing"
)

func BenchmarkB1(b *testing.B) {
    str := "test1.txt, test2.txt"
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ar := regexp.MustCompile(`\s*,\s*`).Split(str, -1)
        var result []string
        for _, x := range ar {
            result = append(result, x) // --> 'test.js', 'test2.py'
        }
        _ = result
    }
}

func BenchmarkB2(b *testing.B) {
    str := "test1.txt, test2.txt"
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ar := strings.Split(str, ",")
        var result []string
        for _, x := range ar {
            result = append(result, strings.TrimSpace(x)) // --> 'test.js', 'test2.py'
        }
        _ = result
    }
}

Result :

$ go test -bench .
BenchmarkB1-4             100000             13048 ns/op
BenchmarkB2-4            3000000               399 ns/op
PASS

Just as expected, the regular expression was slow. And it’s much slower than that of Split() and TrimSpace().

 Share!