4 ms·
So how big does my struct need to be before its more efficient to pass a pointer to it to a function?
by kristianp 10y ago
So how big does my struct need to be before its more efficient to pass a pointer to it to a function?
- Matt3o12_ 10y agoI've often wondered this myself. Perhaps the right answer would be to benchmark and/or use the profiler. On the other handy, I have never really had a situation where I had to pass a strict that was really big (more then 1MB). Most of the time, big data structures are actually just slices, which use pointers to point to the memory address of the underlying array (as far as I understand). So having sich big struct is rather unusual. Maybe it is possible to do with strings, though it would depend on how are strings implemented in go (I would guess they are just slices as well). Furthermore, having big strings 1<x<50 MB) is rather unusual unless the strings can also become really big (1GB in which case you should not probably pass-by-reference or even better, buffer the string because arbitrary length strings can easily cause ram problems).
- echlebek 10y agoIn Go, strings are internally a header that contains a length and a pointer. The bytes of the string itself are heap allocated.
- echlebek 10y agoWell, it depends whether the time spent copying the bytes for the function invocation is less than the time spent garbage-collecting objects that are passed as pointers, and then following those pointers. So as you can imagine, it's highly variable depending on the lifecycle of those objects, how frequently the function is being called, and probably a bunch of other factors like how big your CPU cache is. And then there is the cost of pointer indirection, which can cause cache misses. I don't think there's really a rule of thumb here. Writing benchmarks, and observing the results is about the best you can do.
- deleted 10y ago[deleted]