如何连接 PHP 字符串而不使 PHP 将值从一个位置复制到内存中的另一个位置?

How do I concatenate PHP strings without making PHP copy values from one location to another in memory?

我做了一个函数,它接受任意数量的单词作为参数,并将每个单词的第一个字母大写。

我查看了这个网站:http://www.carlconrad.net/en/2014/03/17/improving-php-performance/ 上面写着:

Avoid string concatenations in loops. When placed in a loop, string concatenation results in the creation of large numbers of temporary objects and unnecessary use of the garbage collector. Both consume memory and can dramatically slow down script execution.

我正在想办法修改下面的代码以使其 运行 更快。有没有另一种方法可以在不依赖原始值的情况下连接 PHP 中的字符串?

我知道在原始 C 语言中,我可以使用字符串的地址指针加上定义范围内的偏移量来添加数据,而不用担心原始字符串被复制到其他地方,来源声称 PHP 在期间做了什么串联。

理想情况下,我希望我的字符串连接像此 C 代码的工作方式一样工作(假设我们在此处的 main() 函数中):

char string[1000];
memcpy(string,'ABCD',4); //place ABCD at start
memcpy(string+4,'EFGH',4); //add EFGH to the string (no previous string copying required)

只是简单的连接,不处理字符串的前一个值。

这是我的 php 代码,需要改进建议:

function capitalize($words){
    $words=$words.' ';
    $returnedwords='';
    $eachword=explode(' ',$words);$numberofwords=count($eachword);
    if ($numberofwords >=1){
        $wordkey=array_keys($eachword);
        for($thiswordno=0;$thiswordno<$numberofwords;$thiswordno++){
            $word=$eachword[$wordkey[$thiswordno]];
            $returnedwords.=' '.strtoupper(substr($word,0,1)).strtolower(substr($word,1));
        }
        return substr($returnedwords,1);
    }
}

我有什么想法可以遵循网站的建议来避免像我这样的循环中的字符串连接吗?

在php中有把字符串首字转为大写的功能

示例 1:字符串的 ucword:

$str = 'this is test value of data';
echo ucwords('this is test value of data');

output: This Is Test Value Of Data

示例 2:从包含多个单词的数组创建 ucword 字符串:

$str = array(
    'this',
    'is',
    'test',
    'VALUE',
    'of',
    'Data'
);

$str = array_map('ucwords', array_map('strtolower', $str));

echo implode(' ', $str);

output: This Is Test Value Of Data

有关更多详细信息,请查看:PHP String Functions