duancan1732 2017-02-14 19:59
浏览 40
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dousenjue3214 2017-02-14 20:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行