note 110545 deleted from language.references by aharvey
| From: | aharvey@php.net | Date: | Tue, 06 Nov 2012 01:15:37 +0000 |
| Subject: | note 110545 deleted from language.references by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191680@lists.php.net to get a copy of this message | ||
Note Submitter: jc (dot) flash (e-snail) gmail (dot) com
----
This is an important info, which I was missing untill today, so pay attention...
Some people think that pass-by-reference speeds up your code, but that's not true...
Lot of people know that references do NOT speed up your code, because PHP does copy-on-write...
But what some people might not know (i didn't), is that references may actualy significantly
SLOW your code DOWN, becouse they DISABLE copy-on-write. I couldn't believe it, so I tested it.
(v. 5.3.10)
<?php
for($i=1;$i<100;$i++){
for($ii=1;$ii<1000;$ii++){
$arr[$i][$ii]=$i*$ii;
}
}
$time=microtime();
?>
here we have two options
1) pass by value:
<?php
$foo=$arr;
?>
2) or pass by reference:
<?php
$foo=&$arr;
?>
<?php
for($i=1;$i<10000;$i++){
// paradox happens here....
// if $foo is reference, whole array is coppied
$bar=$foo;
}
echo microtime()-$time;
?>
They are both effectively pass-by-refference, because of copy-on-write.
But next time, you assign this variable to another, paradox appears, because:
In option 1), this second assign is pass-by-refference (because of copy-on-write)
In option 2), this assign is actual COPY! (copy-on-write is disabled by forcing pass-by-refference
before)
results of microtime() are:
1) 0.002657 // without pass by refference
2) 0.064538 // with pass by refference
Also, lot of built-in php functions (count for example) cannot work with reference, so if you use
reference, they will make a real copy instead, again slowing your code down.