[dev] [commits] Horde branch master updated. 8fb392db7dd8fa42dd7a759be11b1628ee5a7e39

Jan Schneider jan at horde.org
Sat Sep 10 14:40:44 UTC 2011


Zitat von Michael M Slusarz <slusarz at horde.org>:

> Quoting Jan Schneider <jan at horde.org>:
>
>> Zitat von Michael M Slusarz <slusarz at horde.org>:
>>
>>> commit 4797d5ac1c99268d489462c06c1d0404f00d29fa
>>> Author: Michael M Slusarz <slusarz at curecanti.org>
>>> Date:   Fri Sep 9 17:23:08 2011 -0600
>>>
>>>   Some places where we can use references instead of copy-by-value
>>>
>>> framework/Mime/lib/Horde/Mime.php         |    8 ++++----
>>> framework/Mime/lib/Horde/Mime/Address.php |    2 +-
>>> 2 files changed, 5 insertions(+), 5 deletions(-)
>>
>> This doesn't make sense. PHP does copy-on-write, so it doesn't  
>> matter if use references or copy-by-value. If you want to avoid  
>> copying the value into a new variable during the loop, you should  
>> rather loop over the keys instead (if those are really arrays, not  
>> iterators).
>
> You are partially correct.  Not sure what I was looking at, but the  
> changes I made don't affect the original array.  So they don't add  
> anything here (this might be related to other changes, still  
> uncommitted, that I am making to Mail_RFC822 that I may have  
> confused with these).
>
> But when the loop does affect the original array, foreach ($list as  
> $val) is much less efficient than foreach ($list as &$val).  Even if  
> you only alter one variable in the array, the entire array needs to  
> be copied (I personally thought that PHP would be smarter than that  
> - it would only need to copy the array value that changes - but  
> apparently not).

Sure, but you should only use references if you indeed want to change  
the value inside the loop. This is the only valid reason to use  
references here. And using references should be a hint to any  
developer looking at that code that the array values will change.

> And not sure if this is what your are referring to, but this is a  
> terrible idea:
>
> foreach (array_keys($list) as $key) {
>     // Access $list[$key]
> }
>
> This consumes 50% more memory than:
>
> foreach ($list as $val) {
>     // $val
> }

Interesting, I didn't know that. Though it might depend on the ratio  
of array size vs. value sizes. Now that I think of it, it makes sense,  
because you need a complete copy of the array, even if only of the  
array keys. This could only be outweighed if some of the array values  
are larger than the whole array (keys), in terms of internal PHP  
representation.

> reset()/each() is still the much preferred method when dealing with  
> arrays that may be large.

Agreed.

Jan.

-- 
Do you need professional PHP or Horde consulting?
http://horde.org/consulting/



More information about the dev mailing list