How do you know which of the two methods is faster?

I have 2 methods for trimming a domain suffix from a subdomain, and I would like to know which one is faster. How to do it?

2 line cropping methods

+3
source share
1 answer

You can use the built-in testing capabilities go test .

For example ( in the game ):

import (
    "strings"
    "testing"
)


func BenchmarkStrip1(b *testing.B) {
    for br := 0; br < b.N; br++ {
        host := "subdomain.domain.tld"

        s := strings.Index(host, ".")
        _ = host[:s]
    }
}

func BenchmarkStrip2(b *testing.B) {
    for br := 0; br < b.N; br++ {
        host := "subdomain.domain.tld"

        strings.TrimSuffix(host, ".domain.tld")
    }
}

Save this code in somename_test.goand run go test -test.bench='.*'. For me, this gives the following output:

% go test -test.bench='.*'
testing: warning: no tests to run
PASS
BenchmarkStrip1 100000000           12.9 ns/op
BenchmarkStrip2 100000000           16.1 ns/op
ok      21614966    2.935s

benchmark , , 100000000. 100000000 , 12,9 16,1 . , , BenchmarkStrip1 .

, , , , -, .

, , .

+5
source

All Articles