Pointers vs. values in parameters and return values

前端 未结 4 984
悲哀的现实
悲哀的现实 2020-11-22 06:08

In Go there are various ways to return a struct value or slice thereof. For individual ones I\'ve seen:

type MyStruct struct {
    Val int
}

fu         


        
4条回答
  •  再見小時候
    2020-11-22 06:34

    If you can (e.g. a non-shared resource that does not need to be passed as reference), use a value. By the following reasons:

    1. Your code will be nicer and more readable, avoiding pointer operators and null checks.
    2. Your code will be safer against Null Pointer panics.
    3. Your code will be often faster: yes, faster! Why?

    Reason 1: you will allocate less items in the stack. Allocating/deallocating from stack is immediate, but allocating/deallocating on Heap may be very expensive (allocation time + garbage collection). You can see some basic numbers here: http://www.macias.info/entry/201802102230_go_values_vs_references.md

    Reason 2: especially if you store returned values in slices, your memory objects will be more compacted in memory: looping a slice where all the items are contiguous is much faster than iterating a slice where all the items are pointers to other parts of the memory. Not for the indirection step but for the increase of cache misses.

    Myth breaker: a typical x86 cache line are 64 bytes. Most structs are smaller than that. The time of copying a cache line in memory is similar to copying a pointer.

    Only if a critical part of your code is slow I would try some micro-optimization and check if using pointers improves somewhat the speed, at the cost of less readability and mantainability.

提交回复
热议问题