The general rules of thumb are --> don't use references unless you
actually *want* a reference. And don't use references for performance
reasons.
Under PHP 4, it's generally been recommended to use a reference
operator when creating objects.
$obj =& new Object();
PHP uses references internally until it's necessary to create a copy:
$a = array();
$a = $b; // internally, $b is a reference to $a
$b[] = "chocolate"; // at this point, a copy is made, and $b is
modified
So PHP waits until a copy is actually needed before it makes one.
Explicitly making copies incurs overhead because of the concept of
"reference counting". So again, don't use references for performance
reasons.
~Ted
On 23-Jul-08, at 1:07 AM, Yeti wrote:
Hello everyone,
Many of you may be familiar with references in PHP. Now i read
somewhere in the PHP manual that creating references can take longer
than copies. PHP5+ also seems to reference a bit different thant PHP4
did.
Here is some working example code:
<?php
class useless {
var $huge_array;
function __construct() {
$this->huge_array = array();
for ($i = 0; $i < 1024; $i++) $this->huge_array[] = $GLOBALS; //
fill ze array with copies of $GLOBALS array
return true;
}
function useless() {
return $this->__construct();
}
}
$time_start = microtime(true);
$test_obj = new useless();
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "It took {$time} seconds without using the reference operator.\r
\n";
unset($test_obj);
$time_start = microtime(true);
$test_obj =& new useless();
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "It took {$time} seconds using the reference
operator.\r\n########## with obj2 ############\r\n";
$time_start = microtime(true);
$test_obj = new useless();
$obj2 = $test_obj;
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "It took {$time} seconds without using the reference operator.\r
\n";
unset($test_obj);
$time_start = microtime(true);
$test_obj =& new useless();
$obj2 =& $test_obj;
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "It took {$time} seconds using the reference operator.\r\n";
?>
I tested the code in PHP 4.4.7 and in PHP 5.2.5 and the results were
pretty much the same. Using references speeds up the script!
Occasionally obj2-with-references took longer than all the others. But
i don't know if that's to be taken serious.
Now if i do not need a copy, isn't it smarter to use references
instead?
I'm grateful for any ideas, thoughts or experiences
Yeti
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php