Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tail call recursion

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.

like image 964
Dani Avatar asked Nov 25 '25 09:11

Dani


1 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.

like image 98
Seth Carnegie Avatar answered Nov 26 '25 21:11

Seth Carnegie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!