note 97735 deleted from language.variables.scope by danbrown

From: Date: Wed, 05 May 2010 17:44:38 +0000
Subject: note 97735 deleted from language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168981@lists.php.net to get a copy of this message
Note Submitter: rybadour at gmail dot com ---- @moraesdno $GLOBALS isn't always faster. It is only faster when there is only one use of a given variable. When there are more it is significantly better to use the global keyword. Given moraesdno's example the $GLOBALS keyglobal is faster on average by about 1/100,000 of a microsecond. While the code I offer below shows global is faster by 1/10,000 of a microsecond for just 2 variables. Ten times larger than the gain from only using a variable once with $GLOBALS And obviously as the amount of uses for a given variable increases the speed gain for using the global keyword increases. Code: <?php //Using the keyword global $a=1; function sum() { global $a; $a += 1; $a += 1; } $t = microtime(true); for($i=0; $i<1000; $i++) { sum(); } $end = microtime(true)-$t; echo "global keyword: <br />"; echo $end; echo " -- ".$a."<br /><br />"; //Using the superglobal array $a=1; function sum2() { $GLOBALS['a'] += 1; $GLOBALS['a'] += 1; } $t = microtime(true); for($i=0; $i<1000; $i++) { sum2(); } $end2 = microtime(true)-$t; echo '$GLOBALS superglobal: <br />'; echo $end2; echo " -- ".$a."<br><br />"; ?>

« previous php.notes (#168981) next »