Stack overflow or tail recursion?

huangapple go评论61阅读模式
英文:

Stack overflow or tail recursion?

问题

以下是您要翻译的内容:

I'm trying to find out if the following code piece is good or bad practice. It's about a html query string that should be parsed by my API. It's very convenient to use recursion to trim an arbitrary amount of '?' off the query string.

However, I'm wondering if this could potentially result in a stack overflow due to the uncontrollable recursion depth. My hope is that such cases are guaranteed to be tail-optimized but I'm not sure about it. Is there such guarantee?

Demo

#include <string_view>
#include <cstdio>

static auto digest_query(std::string_view query) -> void
{
    if (query.front() == '?') {
        // printf("%.*s\n", (int)query size(), query data());
        return digest_query(query.substr(1));
    }
    // Do other stuff...
}

int main()
{
    digest_query("???????key=value");
}
英文:

I'm trying to find out if the following code piece is good or bad practice. It's about a html query string that should be parsed by my API. It's very convenient to use recursion to trim an arbitrary amount of '?' off the query string.

However, I'm wondering if this could potentially result in a stack overflow due to the uncontrollable recursion depth. My hope is that such cases are guaranteed to be tail-optimized but I'm not sure about it. Is there such guarantee?

Demo

#include &lt;string_view&gt;
#include &lt;cstdio&gt;

static auto digest_query(std::string_view query) -&gt; void
{
    if (query.front() == &#39;?&#39;) {
        // printf(&quot;%.*s\n&quot;, (int)query.size(), query.data());
        return digest_query(query.substr(1));
    }
    // Do other stuff...
}

int main()
{
    digest_query(&quot;???????key=value&quot;);
}

答案1

得分: 2

没有这样的保证。

英文:

> Is there such guarantee?

No there isn't.

答案2

得分: 0

递归深度并非“不受控制”,它确切等于前导'?'的数量。每个级别将在堆栈上托管一个字符串变量,但字符串数据本身分配在堆上。

因此,绝对没有溢出的风险,但这段代码非常低效!它涉及 - 递归调用, - 字符串分配/释放, - 字符串复制。所有这些都是完全无用的。我称之为灾难。

我是否应该补充说,我觉得这段代码相对于正则表达式查询或直接的循环来说,非常难以阅读(出乎意料)?

英文:

The recursion depth is not "uncontrolled", it is exactly equal to the number of leading '?'. Every level will host a string variable on the stack, but the string data itself is allocated on the heap.

So there is absolutely no risk of overflow, but this code is so inefficient ! It will involve - recursive calls, - string allocation/deallocations, - string copies. All of this perfectly useless. I call it disaster.

Should I add that I find it pretty unreadable (so unexpected) compared to a regex query or a straightforward loop ?

huangapple
  • 本文由 发表于 2023年2月10日 15:55:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定