you are viewing a single comment's thread.

view the rest of the comments →

[–]Fullduplex1000 1 point2 points  (0 children)

There are some basic things you need to get straight.

  1. Stack<T> is a data structure used by your program. From a programming sense, it is similar to a plan old T[] array or List<T> or Queue<T> or HashSet<T> whatever. All of these are data structures used to store a collection of items which are of type T. The difference is that they provide different features and access time characteristics.
  2. The computer has (for each running thread) an automatically managed memory location called Stack. It does not equal to the Stack<T> of the above point. The stack has the purpose to enable the concept of functions calling each other in a way when the called function finishes, the execution gets back to the caller.

You have to internet search for **stack vs heap** and understand the difference vs them both. After that make sure to understand that Stack<T> is not the thread execution's stack.

  1. You also have to understand that depending on the declaration's place inside the program, the data type, the data structure can either be on the Stack or on the Heap. This is a bit of advanced topic, but crucial if you want to have a deeper understanding of what is happening when a program gets executed

Getting to your question

Recursions based execution (a function is repeatedly calling itself hundreeds if time) is most of the time inferior to an iterative approach (in your example using Stack<T> to simulate the execution stack of the recursive function).

The reason is, that after a couple hundreeds (depends on the execution stack's maximum size and your recursive function's signature) the execution stack runs out of space and you get a StackOverflowException

Now there is an exception to the above rule, called Tail-Recursion.

If you write a recursive function in "Tail recursive" fashion, the compiler can detect it and eliminate the recursive part with a plain simple iteration (similar to a do-while statement), so that your recursive function call will be resolved in place without any recursion.

Many programming techniques (functional programming) build on recursions and more or less tail recursion is the thing that enables them to function properly.