Allocating on the Stack

Go gets a speed boost by using the stack — and the C vs C++ comment war ignites

TLDR: Go can now keep some temporary data on the stack, turning a potential heap allocation into zero and speeding things up. Comments devolved into a C vs C++ bicker over alloca’s safety and standards, plus debates on whether other languages and profiling could unlock the same gains.

Go just dropped a performance glow-up: if your code hints the right size, the compiler can stash short-lived data on the stack (think: a backpack) instead of the heap (think: a storage unit). Result? That “one allocation” in your slice can secretly become zero — no slowdowns, less work for the garbage collector, and faster, snappier apps. Even with shiny GC upgrades like “Green Tea,” devs cheered: fewer heap trips, more speed.

Then the comments exploded. Old-school C/C++ folks crashed the party with “We’ve had alloca forever,” flexing stack tricks since the 90s. Instantly, pushback: “alloca isn’t even standard in C++ and good luck using it safely.” Cue spicy standards-lawyering and a mini culture war. Meanwhile, the optimists asked if other memory-managed languages could steal the move. Dreamers wanted profile-guided magic: could the compiler learn your app and pre-reserve the perfect stack space? A sober voice warned that making appends purely stack-driven would demand risky runtime changes — the kind that spark “questionable changes” panic.

The memes wrote themselves: “GC hates this one weird trick,” “Stack bros vs Heap heads,” and “prealloc and pray.” Verdict from the crowd: tiny tweak, big win, with bonus drama from the C/C++ peanut gallery.

Key Points

  • Go aims to reduce slowness by minimizing heap allocations, which add garbage collector overhead.
  • Slice append grows capacity by doubling, causing multiple early allocations and garbage in the startup phase.
  • Preallocating slices with make and a known capacity is always correct and can reduce reallocations.
  • With a constant capacity and no escape to heap, the Go compiler can allocate the slice backing store on the stack.
  • Stack allocations are cheaper, impose no GC load, and enable prompt, cache-friendly reuse.

Hottest takes

"you've always had the ability to allocate on the stack using alloca()" — HarHarVeryFunny
"alloca() is not part of the C++ standard" — zabzonk
"Shouldn't other memory-managed languages be able to profit from this as well?" — bertylicious
Made with <3 by @siedrix and @shesho from CDMX. Powered by Forge&Hive.