Removing recursion via explicit callstack simulation

Dev swaps “pretty” code for crash‑proof loops — crowd asks why tools can’t do it

TLDR: A developer shows how to avoid crash‑prone “function calls itself” code by hand‑building a simple loop and stack, trading elegance for safety. The comments split: some insist tools should automate this, while others cheer the speed and stability of DIY loops, asking why mainstream compilers don’t already do it.

A coder showed how to turn those elegant “function-calls-itself” tricks into a down‑and‑dirty loop, all to stop apps from crashing with stack overflows in Node.js and TypeScript. Translation for non‑devs: they replaced a neat, storybook solution with a DIY to‑do list that the computer can handle without fainting. The post demos a hand‑built call stack using simple data records, and admits it’s uglier but safer — especially on really long lists and tree‑shaped data. It’s basically turning a cliff‑hanger into a checklist.

Cue the comments cage match. One camp shrugged, “the compiler should do this” — that’s the tool that turns code into machine instructions — arguing this is a mechanical rewrite most machines could automate. Another camp flexed performance gains: manual stacks plus tail recursion (when the last step is a simple return) mean the hardware “just loves” loops. Meanwhile, a practical crowd asked the obvious: if it’s faster and safer, why don’t big C++ compilers do it by themselves?

Jokes flew about building an “IKEA stack” at home and “loop bros” bench‑pressing arrays. But under the memes was a real split: beauty vs. brawn. Keep the cute recursion and risk crashes, or embrace the messy loop life and let the CPU sprint. Pick your fighter. Node.js TypeScript

Key Points

  • The article describes converting recursive code to an imperative form by simulating the call stack with explicit frames.
  • Motivation is to avoid stack overflows in environments like Node.js when recursion depth becomes large.
  • TypeScript is used for examples; features like type narrowing help implement the approach.
  • A recursive sum over a linked list can overflow; an iterative version using a pointer avoids this by accumulating left-to-right.
  • The technique is largely mechanical, applicable to languages with mutability and parametric polymorphism, though not fully automatable.

Hottest takes

"It can be done mechanically, it's essentially what a compiler does" — juancn
"So, replacing recursion with manually-managed stack gives some performance boost" — Panzerschrek
"I am wondering why no major C++ compiler can do this for me automatically" — Panzerschrek
Made with <3 by @siedrix and @shesho from CDMX. Powered by Forge&Hive.