4 ms·
any thoughts on whether to use values or pointers to large structs? in practice I haven’t seen any major performance overhead when passing values about.
by libguy 7y ago
any thoughts on whether to use values or pointers to large structs?
in practice I haven’t seen any major performance overhead when passing values about.
- 8077628 7y agoI also wonder about this. I think some benchmarks are in order, with checks for the impact of escape analysis/copy to heap.
- lloeki 7y agoPassing pointers is typically a code smell in Go, given that the "don't communicate by sharing, share by communicating" hinges on copying values when passed into e.g channels so as not to have mutexes everywhere, which would defeat the purpose of such a design. Not that you should not have mutexes in idiomatic Go, but they usually have to be warranted for.
- Cthulhu_ 7y agoThere is no straight answer to this, so, it depends. I think it's really one of those problems that isn't important yet until you can actively measure a performance issue. Until then, focus on clarity and functionality; it's much easier to measure and optimize code if your code and its intent is clear. Until then, beware of premature optimization.
- sagichmal 7y agoYou should use pointers if you need to mutate the content of the struct, and values otherwise. Almost all types that could hold a lot of data have reference semantics, so if you have a struct with a large slice, or a large map, all of the actual data is going to be on the heap, and not affect copy performance. The only time you might want to consider using a pointer to improve copy performance is if you have lots of non-heap-allocated data in your struct, and in practice the only way that happens is via large arrays. That is, e.g. `[8192]string`, and not simply `[]string` (which is an efficient slice). But you should never do it preemptively, you should always benchmark both styles and only switch to pointers once you have proof it's meaningfully affecting performance.
- mhh__ 7y agoI don't know what's idiomatic in Go, but I would do whatever makes the code easiest to understand (if that could be an issue). Modern compilers are very good at optimising pass-by-value into a pointer, so write first then measure and then optimise where required.