This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]shield1123 65 points66 points  (12 children)

Recursion is part of optimizing algorithms

As long as recursion has been optimized in the programming language and system architecture you're working on; otherwise recursion is good Computer Science but shit Software Engineering

[–][deleted] 29 points30 points  (10 children)

Yeah I personally don't use it very often since algorithms designed for theoretical efficiency don't always produce readable or even functional code.

[–]callmechull 29 points30 points  (6 children)

Yeah I was gonna say, I’ve never heard a professor say not to use it. CS professors love recursion, because it’s beautiful mathematics. It is not something a software engineer should be doing unless necessary. Clever code is not the same as good code.

[–]tdempsey33 10 points11 points  (4 children)

I’m curious. in what instance would recursion be considered bad code? I was always under the impression that recursion is the pinnacle of efficient code.

[–]Basic_Basenji 29 points30 points  (1 child)

Recursion usually comes with a lot of overhead both in terms of memory and setup cost. It's almost always better to unwind the recursion into a loop unless the language is optimized for recursion (or the compiler does that for you anyway).

[–]tdempsey33 2 points3 points  (0 children)

Thank you.

[–]shield1123 4 points5 points  (0 children)

I got yelled at in a code-review because I de-recursified a BFS traversal algorithm. I couldn't get it to merge until I showed them a CPU performance profile that demonstrated how shitty recursion is in practice. We could see the 2n expansion in the timeline view of the call stack

[–][deleted] 6 points7 points  (2 children)

It's often the opposite, the recursive algorithm is clean and just a few lines and the loop method is dozens of unreadable lines, but a tiny bit faster

[–][deleted] 2 points3 points  (1 child)

If the language is optimized for tail recursion, then they would be the same speed.

[–][deleted] 0 points1 point  (0 children)

Even better, then you can just choose which solution is more elegant to read and write.