有没有一种内存有效的方法来连接 PHP 中的变量?

我有一个超过内存限制的 PHP 脚本。我一直在增加内存,ini_set但我已经达到了物理极限。

所以我宁愿修复代码也不愿添加更多内存。

这是循环中的违规行:

$values_string .= $values . ',';

$values 总是相同长度的 77 个字符(当然是不同的)。

所以我在做的时候读到 PHPconcat实际上创建了第三个变量。我希望避免不必要的临时变量创建。

此外,这是在 40,000 次迭代循环中。有没有办法避免混乱堆积(我的意思是在内存/垃圾收集器中)?

试图增加内存限制ini_set(工作了一段时间)。


手掌心
浏览 162回答 2
2回答

四季花海

你的问题让我想知道有什么区别,并使用 77 个字符的长字符串数组运行了一些测试。结果如下康卡特Start Memory Usage: 2097152 KBPost Array Build Memory Usage: 6291456 KBConcat without Quotes Time: 28.893930912018Post Concat without Quotes Memory Usage: 6291456 KB用引号连接测试不断耗尽内存,即使在低循环量下也失败内爆Start Memory Usage: 2097152 KBPost Array Build Memory Usage: 6291456 KBImplode Time: 19.913722991943Implode Memory Usage: 6291456 KB测试方法set_time_limit(180);function convert_memory_usage($size) {&nbsp; &nbsp; if($size < 1024){&nbsp; &nbsp; &nbsp; &nbsp; return $size . " B";&nbsp; &nbsp; }&nbsp; &nbsp; else if(1048576)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return ($size / 1024) . " KB";&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; return ($size / 1048576) . " MB";&nbsp; &nbsp; }}&nbsp;function implode_array($arr){&nbsp; &nbsp; $str = implode("", $arr);}function concat_without_quotes($arr){&nbsp; &nbsp; $str = "";&nbsp; &nbsp; foreach($arr as $s){&nbsp; &nbsp; &nbsp; &nbsp; $str .= $s;&nbsp; &nbsp; }}function concat_with_quotes($arr){&nbsp; &nbsp; $str = "";&nbsp; &nbsp; foreach($arr as $s){&nbsp; &nbsp; &nbsp; &nbsp; $str = "{$str}{$s}";&nbsp; &nbsp; }&nbsp;}echo "Start Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";$string = "01234567890123456789012345678901234567890123456789012345678901234567890123456";$array = [];for($x = 0; $x < 40000; $x++){&nbsp; &nbsp; array_push($array, $string);}echo "Post Array Build Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";$start = microtime(true);for($x = 0; $x < 10000; $x++){&nbsp; &nbsp; // Change method to loop here&nbsp; &nbsp; implode_array($array);}// And Uncomment as required//echo "Implode Time: " . (microtime(true) - $start) . "</br>";//echo "Implode Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";//echo "Concat with Quotes Time: " . (microtime(true) - $start) . "</br>";//echo "Concat with Quotes Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";//echo "Concat without Quotes Time: " . (microtime(true) - $start) . "</br>";//echo "Concat without Quotes Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";总结 经过这些测试,您可以看到这implode似乎是加入大量strings.用法 $long_string = implode("", $array_of_strings)使用 PHP 7.3.4 版

天涯尽头无女友

正如在此评论中提到的:https&nbsp;:&nbsp;//www.php.net/manual/en/language.operators.string.php#60035,通过将字符串放在双引号内来连接字符串更有效。因此,更有效的连接方式是:$values_string&nbsp;=&nbsp;"{$values_string}{$values},";
打开App,查看更多内容
随时随地看视频慕课网APP