php5:为一个foreach的数组'复制'会产生开销吗?

时间:2009-11-16 07:14:08

标签: php arrays reference

对于foreach(在这种情况下是php5)的数组的'副本'是具有实际开销的立即副本,还是仅仅是一个惰性副本(写入时复制),如果它检测到写入操作只会产生开销?

备选方案,在几个地方注意,是运行foreach over keys($ array) - 这怎么可能真的更快?

2 个答案:

答案 0 :(得分:2)

好的,所以我去了测量它 -

Test This                    And This                       And, uh, This      
---------------------------  ----------------------------   ----------------------------
Setup                        Setup                          Setup                     
---------------------------- ----------------------------   ----------------------------
$i = array_fill(0,1000,'1'); $j = array_fill(0,1000,'1');   $j = array_fill(0,1000,'1');
$c = 0;                      $d = 0;                        $e = 0;
---------------------------  ----------------------------   ---------------------------
Code Under Test              Code Under Test                Code Under Test                    
---------------------------  ------------------------------ --------------------------
foreach ($i as $v)           foreach (array_keys($j) as $k) foreach ($i as &$v)
{ $c+= $v; }                 { $d+= $j[$k]; }               { $e+= $v; }    
---------------------------  ------------------------------ -------------------------
Tear Down                    Tear Down                      Tear Down                          
---------------------------  -----------------------------  -------------------------
print "c = $c";             print "d = $d";                 print "e = $e";                    
---------------------------- -----------------------------  --------------------------
Test for repetitions.  10000         
---------------------------- -----------------------------  -------------------------
c = 10000000                 d = 10000000                   e = 10000000
---------------------------- -----------------------------  -------------------------
Ran in  1.8540189266205      Ran in 4.0039160251617         Ran in 1.9633851051331
---------------------------  -----------------------------  -------------------------
Winner -0.10936617851257     Looser 2.0405309200287         2nd Best             0
---------------------------  ----------------------------  -------------------------

看起来foreach($ a as $ v)比array_keys好得多,使用& v就在中间。

答案 1 :(得分:1)

PHP使用copy-on-write。通过引用传递的速度较慢,因为它必须设置数据结构以维护引用。