0

struct instances are required to be passed as pointers when they are about to change or when they are meant to be shared (e.g. files, handles, etc.). But if I do not expect those (e.g. for a DTO), do I really need to care about copies only for performance reasons?

This question is not equivalent to Pointers vs. values in parameters and return values, since that does not address the choice between value/pointer semantics based on performance issues.

Alirus
  • 472
  • 4
  • 14
  • 1
    https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-escape-analysis.html https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/ – dm03514 Apr 18 '19 at 18:00
  • 2
    Prioritize semantics. If you need pointer semantics, use pointers. Otherwise, use values, unless you detect, measure, profile, and prove a case where pointers deliver better performance. **Pointers do not automatically improve performance.** They increase GC pressure by moving values from the stack to the heap, so the cost of the copy has to be more than the cost of GC. – Adrian Apr 18 '19 at 18:13

1 Answers1

3

Sometimes the performance boost is noticeable and necessary, sometimes its not. The location of data (in terms of stack vs. heap) is a little harder to determine than it is in languages like C and C++, and in the same manner performance is also hard to determine. Performance is usually something you need to dig a little deeper to get insights about rather than sheer speculation on what may or may not be more performant.

If I was you, I would run some benchmarks against whatever function you're referring to, once by passing the struct by reference (pointer) and another time by passing it by value (it gets copied). The benchmarks will run the function a sufficient amount of time to get an average on system metrics and processing time that you can rely on.

Here is a relevant guide on how to create and run benchmarks in Go (it's built in) - https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go