note 110545 added to language.references

From: Date: Mon, 05 Nov 2012 06:06:04 +0000
Subject: note 110545 added to language.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-191672@lists.php.net to get a copy of this message
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. ---- Server IP: 69.147.83.199 Probable Submitter: 195.14.156.37 ---- Manual Page -- http://www.php.net/manual/en/language.references.php Edit -- https://master.php.net/note/edit/110545 Del: integrated -- https://master.php.net/note/delete/110545/integrated Del: useless -- https://master.php.net/note/delete/110545/useless Del: bad code -- https://master.php.net/note/delete/110545/bad+code Del: spam -- https://master.php.net/note/delete/110545/spam Del: non-english -- https://master.php.net/note/delete/110545/non-english Del: in docs -- https://master.php.net/note/delete/110545/in+docs Del: other reasons-- https://master.php.net/note/delete/110545 Reject -- https://master.php.net/note/reject/110545 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#191672) next »