• AllHailTheSheep@sh.itjust.works
    link
    fedilink
    arrow-up
    3
    arrow-down
    1
    ·
    edit-2
    5 hours ago

    I think modern compilers do actually compile recursion to be equivalent with an iterative model.

    edit: yes when possible they will compile to be iterative, but if it can’t be written iteratively it will be a series of calls and returns. depends on the specific type of recursion it looks like.

    • Buddahriffic@lemmy.world
      link
      fedilink
      arrow-up
      1
      ·
      2 hours ago

      At one point I developed a habit of converting any recursive algorithm I was writing into a loop instead, since I knew function calls have overhead and all recursion really does is lets you use the calling stack and flow control as an invisible data structure.

      Then I got a question about parsing brackets properly during an interview and wrote a loop-based parser to solve it and the guy had to fish for a bit before I remembered recursion and realized that’s the answer he was looking for. My mind just wouldn’t consider using a whole calling stack when an integer would do the trick faster.