gpt4 book ai didi

php - 优化 PHP 中的递归方法

转载 作者:行者123 更新时间:2023-12-04 06:59:26 26 4
gpt4 key购买 nike

我正在编写一个文本标签解析器,我目前正在使用这种递归方法来创建 n 个单词的标签。有没有办法可以非递归地完成或至少可以优化?假设 $this->dataArray 可能是一个非常大的数组。

/**
* A recursive function to add phrases to the tagTracker array
* @param string $data
* @param int $currentIndex
* @param int $depth
*/
protected function compilePhrase($data, $currentIndex, $depth){
if (!empty($data)){
if ($depth >= $this->phraseStart){
$this->addDataCount($data, $depth);
}
if ($depth < $this->phraseDepth){
$currentIndex = $currentIndex + 1;
//$this->dataArray is an array containing all words in the text
$data .= ' '.$this->dataArray[$currentIndex];
$depth += 1;
$this->compilePhrase($data, $currentIndex, $depth);
}
}
}

最佳答案

看看能不能用 tail recursion 而不是基于调用的递归。可能需要进行一些重写,但粗略地看一下就可以了。

尾递归非常适合递归函数的子集,并且是发现循环何时可以替代递归以及如何重写的良好实践。

这么说,我不知道 PHP 内部的开销是多少。可能只是一个返回指针类型设置而不是真正的堆栈风。

Turns out about the same. Does PHP optimize tail recursive calls out itself?



这是我的重写,但请注意,我的大脑目前 sleep 不足!
protected function compilePhrase($data, $currentIndex, $depth){
/* Loop until break condition */
while(true) {
if (!empty($data)){
if ($depth >= $this->phraseStart){
$this->addDataCount($data, $depth);
}
if ($depth < $this->phraseDepth){
$currentIndex = $currentIndex + 1;
// A test here might be better than the !empty($data)
// in the IF condition. Check array bounds, assuming
// array is not threaded or anything
$data .= ' '.$this->dataArray[$currentIndex];
$depth += 1;
}else{
break;
}
}else{
break;
}
}
/* Finish up here */
return($this->dataArray);
}

关于php - 优化 PHP 中的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2107166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com