PHP foreach 函数性能

2022-08-30 20:38:39

有谁知道是否这样做

foreach ($user->getFriends() as $friend) {
  // Do something.
}

导致PHP在用户对象上多次调用函数getFriends(),因此这会更有效率吗?

$friends = $user->getFriends();
foreach ($friends as $f) {
 // Do something.
}

答案 1

foreach使用表达式 的结果。你可以这样看:$user->getFriends()

foreach (($user->getFriends()) as $friend) {
    // ...
}

该函数不会被多次调用,因为您传递的是它的结果,而不是函数本身。 不知道函数。foreach


答案 2

下面是一个要处理的代码:

srand();
$asize = 1000000;
$a = array();
for ($x=1;$x<=$asize;$x++) $a[]=rand();


$i=0;
$s = microtime(true);
foreach($a as $k=>$v) {
    ++$a[$k];
}
$e = microtime(true);
dolog($s,$e,'FOREACH-KEY');

$i=0;
$s = microtime(true);
foreach($a as &$v) {
    ++$v;
}
$e = microtime(true);
dolog($s,$e, 'FOREACH-PTR');

$i=0;
$s = microtime(true);
for ($x=0;$x<$asize;$x++){
    ++$a[$x];
}
$e = microtime(true);
dolog($s,$e,'FOR');

function awpp(&$item,$key){
    ++$item;
}

$s = microtime(true);
array_walk($a, 'awpp');
$e = microtime(true);
dolog($s,$e,'ARRAY_WALK');

reset($a);
$s = microtime(true);
while (list($k, $v) = each($a)) {
    ++$a[$k];
}
$e = microtime(true);
dolog($s,$e,'EACH');

reset($a);
$s = microtime(true);
$node = current($a);
++$node;
while($node=next($a)) {
    ++$node;
}
$e = microtime(true);
dolog($s,$e,'NEXT');

结果:

FOREACH-KEY Start: 1367595478.8087210655, End: 1367595479.2945981026, DIFF: 0.4858770370
FOREACH-PTR Start: 1367595479.2946701050, End: 1367595479.4266710281, DIFF: 0.1320009232
FOR Start:         1367595479.4267220497, End: 1367595479.6769850254, DIFF: 0.2502629757
ARRAY_WALK Start:  1367595479.6770300865, End: 1367595481.1930689812, DIFF: 1.5160388947
EACH Start:        1367595481.1931140423, End: 1367595482.5088000298, DIFF: 1.3156859875
NEXT Start:        1367595482.5088429451, End: 1367595483.2801001072, DIFF: 0.7712571621

因此,最快的是有指针和没有键值的 foreach


推荐