如何找出2种方法中哪一种更快?

I have 2 methods to trim the domain suffix from a subdomain and I'd like to find out which one is faster. How do I do that?

2 string trimming methods

You can use the builtin benchmark capabilities of go test.

For example (on play):

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

Store this code in somename_test.go and 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

The benchmark utility will attempt to do a certain number of runs until a meaningful time is measured which is reflected in the output by the number 100000000. The code was run 100000000 times and each operation in the loop took 12.9 ns and 16.1 ns respectively. So you can conclude that the code in BenchmarkStrip1 performed better.

Regardless of the outcome, it is often better to profile your program to see where the real bottleneck is instead of wasting your time with micro benchmarks like these.

I would also not recommend writing your own benchmarking as there are some factors you might not consider such as the garbage collector and running your samples long enough.