为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
手掌心 2021-11-13 16:58:47
我有一个超过内存限制的 PHP 脚本。我一直在增加内存,ini_set但我已经达到了物理极限。所以我宁愿修复代码也不愿添加更多内存。这是循环中的违规行:$values_string .= $values . ',';$values 总是相同长度的 77 个字符(当然是不同的)。所以我在做的时候读到 PHPconcat实际上创建了第三个变量。我希望避免不必要的临时变量创建。此外,这是在 40,000 次迭代循环中。有没有办法避免混乱堆积(我的意思是在内存/垃圾收集器中)?试图增加内存限制ini_set(工作了一段时间)。
查看完整描述

2 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

你的问题让我想知道有什么区别,并使用 77 个字符的长字符串数组运行了一些测试。


结果如下


康卡特


Start Memory Usage: 2097152 KB

Post Array Build Memory Usage: 6291456 KB

Concat without Quotes Time: 28.893930912018

Post Concat without Quotes Memory Usage: 6291456 KB

用引号连接


测试不断耗尽内存,即使在低循环量下也失败


内爆


Start Memory Usage: 2097152 KB

Post Array Build Memory Usage: 6291456 KB

Implode Time: 19.913722991943

Implode Memory Usage: 6291456 KB

测试方法


set_time_limit(180);


function convert_memory_usage($size) {

    if($size < 1024){

        return $size . " B";

    }

    else if(1048576)

    {

        return ($size / 1024) . " KB";

    }else{

        return ($size / 1048576) . " MB";

    }


function implode_array($arr){

    $str = implode("", $arr);

}


function concat_without_quotes($arr){

    $str = "";

    foreach($arr as $s){

        $str .= $s;

    }

}


function concat_with_quotes($arr){

    $str = "";

    foreach($arr as $s){

        $str = "{$str}{$s}";

    } 

}


echo "Start Memory Usage: " . convert_memory_usage(memory_get_usage(true)) . "<br/>";


$string = "01234567890123456789012345678901234567890123456789012345678901234567890123456";

$array = [];

for($x = 0; $x < 40000; $x++){

    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++){

    // Change method to loop here

    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 版


查看完整回答
反对 回复 2021-11-13
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

正如在此评论中提到的:https : //www.php.net/manual/en/language.operators.string.php#60035,通过将字符串放在双引号内来连接字符串更有效。因此,更有效的连接方式是:

$values_string = "{$values_string}{$values},";


查看完整回答
反对 回复 2021-11-13
  • 2 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信