dongxian7194 2014-03-27 10:39 采纳率: 0%
浏览 81
已采纳

在结构“函数”中使用指针与复制

I'm rather new to Go, and I really can't decide when to use a pointer vs a copy when writing struct "functions" (is that the proper term?)

type Blah struct {
    c complex128
    s string
    f float64
}

func (b * Blah) doPtr() {
    fmt.Println(b.c, b.s, b.f);
}

func (b Blah) doCopy() {
    fmt.Println(b.c, b.s, b.f);
}

Now, my C++ background tells me doPtr is more efficient in both speed and memory, however a lot of examples use doCopy unless you're modifying the object, so am I missing something?

  • 写回答

2条回答 默认 最新

  • duanli0162 2014-03-27 12:29
    关注

    [Go] Frequently Asked Questions (FAQ)

    Should I define methods on values or pointers?

    For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.

    For performance issues, don't guess. Run a benchmark. For example,

    file: bench_test.go

    package main
    
    import (
        "testing"
    )
    
    type Blah struct {
        c complex128
        s string
        f float64
    }
    
    func (b *Blah) doPtr() {
    }
    
    func (b Blah) doCopy() {
    }
    
    func BenchmarkDoPtr(b *testing.B) {
        blah := Blah{}
        for i := 0; i < b.N; i++ {
            (&blah).doPtr()
        }
    }
    
    func BenchmarkDoCopy(b *testing.B) {
        blah := Blah{}
        for i := 0; i < b.N; i++ {
            blah.doCopy()
        }
    }
    

    Output:

    $ go test -bench=.
    testing: warning: no tests to run
    PASS
    BenchmarkDoPtr  2000000000           1.26 ns/op
    BenchmarkDoCopy 50000000            32.6 ns/op
    ok      so/test 4.317s
    $
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法