what is the difference between a recursive version of "find" and a not recursive one?

309 views Asked by At

In the book Accelerated C++ Programming, on page 205, there are the two following implementation of find

 template <class In, class X> In find(In begin, In end, const X& x)

I am interested in knowing what is any difference in terms of performance (whether it's actually the same after the compilation?) of the following two implementations.

non-recursive

template <class In, class X> In find(In begin, In end, const X& x)
{
    while (begin != end && *begin != x)
        ++begin;
    return begin;
}

recursive

template <class In, class X> In find(In begin, In end, const X& x)
{
    if (begin == end || *begin == x)
        return begin;
    begin++;
    return find(begin, end, x);
}

By using Compiler Explorer suggested by Kerrek I got the following

non-recursive https://godbolt.org/g/waKUF2

recursive https://godbolt.org/g/VKNnYZ

It seems to be exactly the same after the compilation? (If I use the tool correctly.. Sorry, I am very new to C++)

2

There are 2 answers

0
nopjmp On BEST ANSWER

Recursive functions will add additionally elements on the stack. This can potentially cause stackoverflow errors depending on the state of the stack before starting recursion and the number of times you recurse.

Each function call pushes data onto the stack which includes the return address. This continues until the data is found. At this time, all of the functions will start to return the value that the last function returned until the we finally get back to the function that called the original find.

The exact amount of data stored for each function call depends on the calling convention and architecture. There is also overhead from pushing data on the stack which can make the algorithm slower, but that depends on the algorithm.

This is strictly for recursion that is not tail call optimized.

1
Shashi Kundan On

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant".

Check out some of the comparisons: Recursion vs Iteration