gpt4 book ai didi

php - 为什么在此代码中通过引用传递速度较慢?

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

我遇到了一些看起来很奇怪的性能问题。运行这段代码:

<?php

function test_ref(&$test)
{
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}
}

function test()
{
$test = array();
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}

return $test;
}

$scriptstart = microtime(true);
$test = array();
test_ref($test);
$sum = 0;

foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}

echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";

$scriptstart = microtime(true);
$test = test();
$sum = 0;

foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}

echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";

?>

我得到这些结果:

sum 548521
time taken 12.37544798851
sum 551236
time taken 0.29530310630798

这是怎么回事?这似乎与我将子数组插入数组这一事实有关,尽管我不明白为什么按引用传递应该慢得多。

(这是在带有 Suhosin 补丁 0.9.9.1 的 PHP 版本 5.3.3-7+squeeze14 上)

(编辑:修复了未设置变量的使用,仍然是相同的结果)

最佳答案

您正在从另一个范围访问值 - 这总是比仅使用在函数本身内定义的值慢。这是一篇解释它的不错的博客文章,尽管这不是它的主要主题:PHP internals: When does foreach copy?

关于php - 为什么在此代码中通过引用传递速度较慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799627/

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