r/learnprogramming • u/Temporary-Warthog250 • 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
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.