douchuilai2355 2019-02-21 12:00
浏览 46
已采纳

有什么更有效的方法,可以返回指向uint或uint的指针?

In Go, what is more efficient to return from a function: returning a uint or returning a *uint?

The function is called in the inner for-loop of a cpu-intensive library.

  • 写回答

1条回答 默认 最新

  • dongqiao6445 2019-02-21 12:08
    关注

    In general, whenever efficiency is the question, you should run benchmarks.

    Let's create very simple examples:

    func fuint() uint {
        return 0
    }
    
    func fpuint() *uint {
        var i uint
        return &i
    }
    

    And the benchmarking code:

    func BenchmarkUint(b *testing.B) {
        for i := 0; i < b.N; i++ {
            fuint()
        }
    }
    
    func BenchmarkPuint(b *testing.B) {
        for i := 0; i < b.N; i++ {
            fpuint()
        }
    }
    

    One thing to look out for: since we have very simple functions, code optimization might render the result useless (e.g. we might see the same result).

    So instead we should test by disabling compiler optimizations. So let's test it like this:

    go test -gcflags '-N -l' -bench . -benchmem
    

    The test results:

    BenchmarkUint-4     500000000        3.21 ns/op      0 B/op     0 allocs/op
    BenchmarkPuint-4    100000000       22.4 ns/op       8 B/op     1 allocs/op
    

    Just as we could have guessed: allocating an uint value and returning a pointer to it is slower and requires an allocation (on the heap), while returning a simple uint value does not.

    But don't think this is always the case. During this test, we disabled compiler optimizations. When you compile your app to production, you will obviously not disable optimizations, so your real-life examples might not have such big difference, or no difference at all. Test / benchmark your actual code to see if returning a pointer actually makes any noticeable difference.

    For reference, here is the result with compiler optimizations enabled (default behavior):

    go test -bench . -benchmem
    
    BenchmarkUint-4     2000000000         0.35 ns/op        0 B/op      0 allocs/op
    BenchmarkPuint-4    2000000000         0.35 ns/op        0 B/op      0 allocs/op
    

    We see no difference for fuint() and fpuint() at all in the specific examples above.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化