Sunday, February 13, 2011

Does foreach always create a copy on a none reference in PHP?

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.

  • 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.

    enobrev : although php5 now has references in foreach, so you could do foreach(getData() as &$data). I use this with arrays all the time, but I've no idea the outcome in the instance of a function call
    From Greg

0 comments:

Post a Comment