note 36105 rejected from language.references.pass by pollita

From: Date: Thu, 25 Sep 2003 23:12:15 +0000
Subject: note 36105 rejected from language.references.pass by pollita
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57144@lists.php.net to get a copy of this message
Note Submitter: ---- I wrote a short program to compare the speed of pass by reference with big strings vs pass by value: The code was as follows: <?php function m_time () { list ($mt_micros,$mt_seconds) = explode (' ',microtime ()); return ((float) $mt_seconds + (float) $mt_micros); } function stopwatch ($sw_code) { $sw_start = m_time (); eval ($sw_code); $sw_end = m_time (); return ($sw_end - $sw_start); } function filetostring ($fs_filename,$fs_readmode = 'rb') { if ((file_exists ($fs_filename)) && (is_file ($fs_filename)) && (is_readable ($fs_filename)) && ($fs_handle = fopen ($fs_filename,$fs_readmode)) && (flock ($fs_handle,LOCK_SH))) $fs_buffer = fread ($fs_handle,filesize ($fs_filename)); else $fs_buffer = NULL; if ($fs_handle != NULL) { flock ($fs_handle,LOCK_UN); fclose ($fs_handle); } return ($fs_buffer); } function reftext (&$ref) { echo ($ref); } function valtext ($val) { echo ($val); } function testref () { global $text; for ($x = 0; $x < 50; $x++) { reftext ($text); } } function testval () { global $text; for ($x = 0; $x < 50; $x++) { valtext ($text); } } $text = filetostring ('path/to/a/big/text/file'); ob_start (); $time1 = stopwatch ('testref ();'); ob_end_clean (); ob_start (); $time2 = stopwatch ('testval ();'); ob_end_clean (); echo ('<br>Pass by reference processing time: '.$time1.'<br>'); echo ('Pass by value processing time: '.$time2.'<br>'); ?> I gave it a text file of about 100K to work with and ran it a few times. There was no significant difference in speed between the pass by reference version of the function and the pass by value version. I increased the number of iterations in the loop to 100 and found under those circumstances pass by reference was slightly faster (1.2 seconds vs 1.5 seconds) From this the conclusion is that, as far as simple data types such as strings or arrays go, pass by reference is really only worth it if you're handling massive amounts of data. Under most circumstances, passing by value should be fine.

« previous php.notes (#57144) next »