问题描述
foreach
会根据以下条件对数组的副本进行操作: http://php.net/manual/en/migration70.incompatible.php
foreach
in PHP7 by default, when iterating by value, operates on a copy of the array according to: http://php.net/manual/en/migration70.incompatible.php
仅在对数组或值进行更改时,它才懒地创建副本吗?还是总是创建副本并实质上使引用循环实现性能优化?
Does it lazily create a copy only if there are changes made to the array or a value or will it always make a copy and in essence make looping over references a performance optimization?
此外,对象数组是否仍然循环/提供对象引用?还是他们实际上还会为foreach
创建副本并按值返回对象?
Also, do arrays of objects still loop over/give you references of the objects? Or will they actually also create copies for the foreach
and return the objects by value?
推荐答案
在PHP 7中,如果您按值迭代数组,则只有在实际修改了数组的情况下,复制才会延迟进行.
In PHP 7, if you iterate an array by value, the copy will be done lazily, only when and if the array is actually modified.
如果您改为通过引用迭代数组,则将在循环开始时执行分隔.如果当前在多个位置使用该数组,则此分隔将导致副本.
If you iterate an array by reference instead, a separation will be performed at the start of the loop. If the array is currently used in more than one place, this separation will lead to a copy.
此外,通过引用进行迭代意味着a)数组必须包装到引用中,并且b)每个元素也必须包装在引用中.创建引用包装是一项昂贵的操作,因为它需要分配.
Furthermore iterating by reference means that a) the array has to be wrapped into a reference and b) each element has to be wrapped in a reference as well. Creating a reference wrapper is an expensive operation, because it requires allocation.
此外,通过引用进行迭代还要求我们使用修改安全的迭代机制.通过在数组中注册迭代器,并在各种数组修改操作中检查可能受影响的迭代器,可以进行此操作.
Additionally iteration by reference requires us to use a modification-safe iteration mechanism. This works by registering the iterator with the array and checking for potentially affected iterators in various array modification operations.
因此,不,通过引用进行迭代当然不是优化,而是一种非优化.通常使用引用.
So no, iterating by reference is certainly not an optimization, it's a de-optimization. Using references usually is.
这篇关于PHP7中的foreach更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!