Go:基于类的方法比功能的方法更有效吗? [关闭]

I am curious if a class-based approach using structs and functions on those structs is more performant in Golang?

So far I have been unable to unearth any resources that compare the two different techniques.

This question came out of a conversation when I was told using a class-based approach to coding is more performant in Javascript than functional.

You can actually test this in go!

In your code you can create a method and the equivalent function. I'm doing this in a main.go file.

type A string
func (a A) Demo(i int) {}
func Demo(a A, i int) {}

Then create a benchmark for it in the test file (main_test.go for me).

func BenchmarkMethod(b *testing.B) {
    var a A = "test"
    var i int = 123

    for n := 0; n < b.N; n++ {
        a.Demo(i)
    }
}

func BenchmarkFunction(b *testing.B) {
    var a A = "test"
    var i int = 123

    for n := 0; n < b.N; n++ {
        Demo(a, i)
    }
}

Then test the benchmarks with go test -bench=.

BenchmarkMethod-8       2000000000           0.27 ns/op
BenchmarkFunction-8     2000000000           0.29 ns/op
PASS

You can update your method and function to do the same thing to see how that affects things.

func (a A) Demo(i int) string {
    return fmt.Sprintf("%s-%d", a, i)
}

func Demo(a A, i int) string {
    return fmt.Sprintf("%s-%d", a, i)
}

And testing this still gets me nearly identical perf.

$ go test -bench=.
BenchmarkMethod-8       10000000           233 ns/op
BenchmarkFunction-8     10000000           232 ns/op
PASS

So short answer - I highly doubt there is any significant performance difference between the two, and if there is it looks like any other code you run is likely to have a larger impact than using methods vs functions.