gpt4 book ai didi

php - PHP 的 substr 效率如何?

转载 作者:可可西里 更新时间:2023-11-01 12:52:55 24 4
gpt4 key购买 nike

我正在用 PHP 编写一个解析器,它必须能够处理内存中的大型字符串,所以这是一个有点重要的问题。 (即,请不要“过早优化”火焰我,拜托)

substr 函数是如何工作的?它是在内存中复制字符串数据的第二个副本,还是引用原始数据?我是否应该担心在循环中调用 $str = substr($str, 1);

最佳答案

如果您真的在研究效率,您将需要为您的字符串保留一个指针 - 我的意思是 index。许多字符串函数接受一个偏移量来开始操作(比如 strpos() 的第三个参数)。通常我会建议编写一个对象来包装此功能,但如果您希望经常使用它,那可能会导致性能瓶颈。这是我的意思的一个例子(没有 OO):

while ($whatever) {
$pos = strpos($string, $myToken, $startIndex);
# do something using $pos
$startIndex = $pos;
}

如果需要,您可以编写自己的包装类来执行这些字符串操作,看看它是否对速度有影响:

class _String {
private $string;
private $startIndex;
private $length;
public function __construct($string) {
$this->string = $string;
$this->startIndex = 0;
$this->length = strlen($string);
}
public function substr($from, $length = NULL) {
$this->startIndex = $from;
if ($length !== NULL) {
$this->endIndex = $from + $length;
}
}
# other functions you might use
# ...
}

关于php - PHP 的 substr 效率如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2813119/

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