Hacker News new | ask | show | jobs
by pcwalton 2817 days ago
You can't avoid allocating using the same techniques as in C++. In Go you have to know the intricacies of escape analysis to avoid allocation: objects are heap allocated "by default" and sometimes optimized to be stack allocated. In C++ there is no implicit heap allocation and usually no need for escape analysis.

As a practical example, capturing variables in a closure will usually cause them to be heap allocated in Go, but in C++ capturing has no effect on variable storage.

3 comments

It seems to me that you're not really taking a charitable interpretation of GP's comment. For example, in my game development experience (granted, I'm 6 years removed from that industry) we often relied on object pools to avoid allocation. You don't need to know anything about Go's escape analysis to use a pool to avoid allocation, as far as I can tell. Could you explain your position further?
Go language constructs allocate in ways that are not immediately obvious. So using object pools is not sufficient to avoid allocation in Go as compared to, say, C++.

In my view (which is the dominant view among compiler engineers for GC'd languages), spending a lot of effort to avoid allocation is a poor use of programmer time in a GC'd language. It is better to just improve the GC to make allocation fast. In a properly designed generational GC like that of Java HotSpot, allocation is about 5 instructions. That is a game changer: allocation is as cheap as a function call plus the prologue.

Unfortunately, Go's designers have so far not deployed generational GC, which is why we keep having these threads about avoiding allocation. (I've seen indications in the last couple of weeks that Go may finally be moving to a generational GC, though, and I hope they do.)

Anyone doing HTML 5/Flash like games in Go doesn't need to worry like if they are writting the next Fortnight in Vulkan.
This is why I've been careful to say "CPU-intensive workloads" and not "games", because not all games are CPU-intensive workloads.
You weren't careful to say it in this subthread though. I had a whole response written up to talk about how you're being completely unreasonable with regards to most gaming projects before I saw this clarification. Now all that effort is wasted! ;)
Ah, sorry I missed it.

Then I fully agree with you.

You’re splitting hairs. Yes, you need to reason about escape analysis. This is pretty easy, especially since the compiler will tell you when things escape. It’s certainly easier than... well, pretty much anything in C++. :)