英文:
Go: Is a class-based approach more performant than functional?
问题
我很好奇在Golang中使用基于类的结构体和函数是否更高效?
到目前为止,我还没有找到比较这两种不同技术的资源。
这个问题是在一次对话中提出的,当时有人告诉我,在JavaScript中使用基于类的编程方法比函数式编程更高效。
英文:
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.
答案1
得分: 7
你可以在Go中实际测试这个!
在你的代码中,你可以创建一个方法和一个等效的函数。我在一个main.go
文件中进行了这样的操作。
type A string
func (a A) Demo(i int) {}
func Demo(a A, i int) {}
然后,在测试文件中(对我来说是main_test.go
),为它创建一个基准测试。
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)
}
}
然后,使用go test -bench=.
来测试基准。
BenchmarkMethod-8 2000000000 0.27 ns/op
BenchmarkFunction-8 2000000000 0.29 ns/op
PASS
你可以更新你的方法和函数,使它们执行相同的操作,看看对性能有什么影响。
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)
}
测试结果显示,它们的性能几乎相同。
$ go test -bench=.
BenchmarkMethod-8 10000000 233 ns/op
BenchmarkFunction-8 10000000 232 ns/op
PASS
所以简短的答案是 - 我非常怀疑这两者之间存在任何显著的性能差异,如果有的话,似乎你运行的其他代码对性能的影响可能比使用方法和函数更大。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论