r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

9

u/AlSweigart Author: ATBS Apr 05 '22

Yes, but I always hold off on performance claims until I run code under a profiler. I've had some recursive code end up being faster than an iterative version. (Not sure how that happened.)

Also, to be specific, the stack overflow happens if you have an extremely deep tree. Like, it could be a linked list (which is basically a unary tree) that is a couple thousand nodes long. If you had an extremely large but shallow tree, you won't have a stack overflow.

And many interpreters/compilers don't have tail call optimization, including the main ones for Python, JavaScript, and Java. I hold the opinion that tail call optimization should never be used.

All recursive functions can be implemented iterative using a loop and stack. If you are doing tail recursion, it's because your recursive algorithm doesn't require the call stack. So iteratively you can implement it as a loop and a stack without the stack, so why not just use a loop? Often times you have to mangle the code and decrease readability to make it tail recursive, so I'd just go with a simple loop every time.

I can't think of a tail recursive function that wouldn't be improved by just using a loop.

1

u/flank-cubey-cube Apr 05 '22 edited Apr 05 '22

Yes, but I always hold off on performance claims until I run code under a profiler. I've had some recursive code end up being faster than an iterative version. (Not sure how that happened.)

True!

(For some reason I can't quote on comments besides the 1st one)

And I should have specified that in my comment that that is only true for deep trees. I came across this because I was unit testing a data structure and created a ridiculously large tree.

And your point on tail recursion is so true! The true reason they exist is to impress interviewers.