DEV Community

Cover image for Format a text in GO better than fmt

Format a text in GO better than fmt

Ushakov Michael on January 14, 2024

Format a text in GO better then fmt Looking at the article title, we should clarify what means better and what is text formatting. Lets...
Collapse
 
marcello_h profile image
Marcelloh

I've tried it:

func Benchmark_StringFormatter(b *testing.B) {
    template := "Hello: {username}, you earn {amount} $"
    args := map[string]any{"username": "Harry", "amount": 1000}
    result := stringFormatter.FormatComplex(template, args)
    assert.Equal(b, "Hello: Harry, you earn 1000 $", result)

    b.ResetTimer()

    for i := 0; i < b.N; i++ { // use b.N for looping
        result = stringFormatter.FormatComplex(template, args)
        _ = result
    }
}

func Benchmark_NormalFormatter(b *testing.B) {
    template := "Hello: %s, you earn %d $"
    args := map[string]any{"username": "Harry", "amount": 1000}
    result := fmt.Sprintf(template, args["username"], args["amount"])
    assert.Equal(b, "Hello: Harry, you earn 1000 $", result)

    b.ResetTimer()

    for i := 0; i < b.N; i++ { // use b.N for looping
        result := fmt.Sprintf(template, args["username"], args["amount"])
        _ = result
    }
}
Enter fullscreen mode Exit fullscreen mode

and the result on my machine (mac M3):

goos: darwin
goarch: arm64
Benchmark_NormalFormatter-8     17027253            68.86 ns/op       32 B/op          1 allocs/op
Benchmark_StringFormatter-8     15007972            80.71 ns/op      100 B/op          2 allocs/op
PASS
Enter fullscreen mode Exit fullscreen mode

Normal seems faster and less allocations

Collapse
 
evillord666 profile image
Ushakov Michael • Edited

@marcello_h, Repo contains benchmarks, my screenshots were obtained on i7 CPU by running on a single core as follows (also running on another machine on i5):

  • to see Format result - go test -bench=Format -benchmem -cpu 1
  • to see fmt result - go test -bench=Fmt -benchmem -cpu 1

I've runned with large statistic ~100 times, and i could say that these vales ratio persists, and sf is faster than fmt