I'm implementing a function as following:
void Add(list* node)
{
if(this->next == NULL)
this->next = node;
else
this->next->Add(node);
}
As it seems Add is going to be tail-called in every step of the recursion.
I could also implement it as:
void Add(list *node)
{
list *curr = this;
while(curr->next != NULL) curr = curr->next;
curr->next = node;
}
This will not use recursion at all.
Which version of this is better? (in stack size or speed)
Please don't give the "Why don't use STL/Boost/whatever?" comments/answers.
They probably will be the same performance-wise, since the compiler will probably optimise them into the exact same code.
However, if you compile on Debug settings, the compiler will not optimise for tail-recursion, so if the list is long enough, you can get a stack overflow. There is also the (very small) possibility that a bad compiler won't optimise the recursive version for tail-recursion. There is no risk of that in the iterative version.
Pick whichever one is clearer and easier for you to maintain taking the possibility of non-optimisation into account.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With