简体   繁体   English

“查找”的递归版本和非递归版本有什么区别?

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

In the book Accelerated C++ Programming , on page 205, there are the two following implementation of findAccelerated C++ Programming一书中,第 205 页,有以下两个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通过使用 Kerrek 建议的编译器资源管理器,我得到了以下信息

non-recursive https://godbolt.org/g/waKUF2非递归https://godbolt.org/g/waKUF2

recursive https://godbolt.org/g/VKNnYZ递归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++) (如果我正确使用该工具..对不起,我对 C++ 很陌生)

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.这可能会导致 stackoverflow 错误,具体取决于开始递归之前的堆栈状态和递归次数。

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 .这时候,所有的函数都会开始返回上一个函数返回的值,直到我们最终回到调用原始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.这严格适用于未经过尾调用优化的递归。

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查看一些比较: 递归与迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM