[HN Gopher] Optimizing Heap Allocations in Go: A Case Study
___________________________________________________________________
Optimizing Heap Allocations in Go: A Case Study
Author : ingve
Score : 37 points
Date : 2025-04-18 19:53 UTC (3 days ago)
(HTM) web link (www.dolthub.com)
(TXT) w3m dump (www.dolthub.com)
| returningfory2 wrote:
| > It's possible that this is a compiler bug. It's also possible
| that there's some fringe case where the reference actually can
| escape via that method call, and the compiler doesn't have enough
| context to rule it out.
|
| Here's an example, I think: suppose the method spawns a new
| goroutine that contains a reference to `chunkStore`. This
| goroutine can outlive the `ReadBytes` function call, and thus Go
| has to heap allocate the thing being referenced.
|
| In general, this kind of example makes me suspect that Go's
| escape analysis algorithm treats any method call as a black box
| and heap allocates anything being passed to it by reference.
| athorax wrote:
| The notion of stack vs heap allocation isn't something that even
| exists in the language. Users are expected to not worry about
| it... until, of course, until you're optimizing performance and
| you need to worry about it.
|
| This is one of the best and worst aspects with Go. Anyone can
| write pretty performant code without having to understand the
| underlying memory model. If you get to the point where you are
| trying to optimize at this level, the benefits of using a more
| approachable language start to fall apart and you spend more time
| chasing implementation details.
| nu11ptr wrote:
| In general, it is a win, since it lets you code faster and
| 80-90% the performance doesn't matter. Over time, you learn
| generally what leads to heap allocs and what doesn't. In rare
| hot spot, using -m will show you the allocations and you can
| optimize.
| athorax wrote:
| I would generally agree. It's good enough performance for
| most applications. For those that it isn't fast enough for
| (even with optimizations like these), it still allows for
| rapid prototyping to arrive at that conclusion.
| Ygg2 wrote:
| I think same applies to any GC language. Ride is fun until GC
| starts either taking too much time, too much memory or taking
| too much of CPU.
| 38 wrote:
| instead of this: t.Buf = []byte{}
|
| you can just do: t.Buf = nil
___________________________________________________________________
(page generated 2025-04-21 23:00 UTC)