views:

386

answers:

1

I'm wondering if PHP has this optimization built in. Normally when you call foreach without using a reference it copies the passed array and operates on it. What happens if the reference count to that array is only 1?

Say for example if getData returns some array of data.

foreach(getData() as $data)
    echo $data;

Since the array returned by getData() only has one reference shouldn't it just be used by reference and not copied first or does php not have this optimization?

This seems like a simple optimization that could help a lot of badly written code.

+3  A: 

I can't say for certain, but PHP normally uses "copy on write", so everything is a reference until you try to write to it, at which time a copy is made and you write to the copy.

Greg
enobrev