Thank you for your reply, Chris. ----- Original Message ----- From: "Chris Adams" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Wednesday, March 14, 2001 3:50 PM Subject: Re: [PHP] foreach() faster than while()? > On 13 Mar 2001 18:10:45 -0800, Yasuo Ohgaki <[EMAIL PROTECTED]> wrote: > >It seems foreach() operates much faster than equivalent while() loop. > >This is result is not what I expect. Foreach() operates on copy of array and I > >thought it would work a little slower than while(). > > Copies aren't necessarily copies - Zend includes a feature where a new variable > will point at the old one until something changes - if all you're doing is > reading that data, that never happens and it never needs to copy the actual > data. I completly forgot about this great PHP4 feature!! It raises another question: Huge/large function parameter, that is passed by value, does not have to be a reference unless programmer needs to change the value? I changed the test code to see what happens. The result was the same. This implies programmer should not use pass by reference unless programmer want to change parameter. (This fact makes my PHP code cleaner :-) Function parameter: Pass by Value and Pass by Reference. Parameter: Single 512KB string read from /dev/urandom Iterations: 100,000 times ======= RESULT =========== Array ( [0] => Array ( [name] => Start [time] => 984556336.83792900 [diff] => - [total] => 0 ) [1] => Array ( [name] => Marker: PASS BY VALUE [time] => 984556338.39530900 [diff] => 1.557380 [total] => 1.557380 ) [2] => Array ( [name] => Marker: PASS BY REFERENCE [time] => 984556339.93990100 [diff] => 1.544592 [total] => 3.101972 ) [3] => Array ( [name] => Stop [time] => 984556339.94007500 [diff] => 0.000174 [total] => 3.102146 ) ) ==================================== > Your while loop does two variable assignments in each loop and I doubt the > underlying engine is smart enough to play the same trick with the variables in > a list() assignment. Even if it was, it'd still have the difference of doing it > twice with whatever additional overhead list() imposes. Agreed. list() or/and each() must be making the difference. > Disclaimer: This is all speculation. I could quite easily be wrong. If you want > a sure answer, take a look at the source. I agree with you and it sound fair explanation to me. >From now on, I decided to use foreach instead of while whenever appropriate. I'll look into the source when I have a time. It's a great finding to me that I don't have use "pass by reference" for large parameters. Thanks again. -- Yasuo Ohgaki -- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to