note 97735 added to language.variables.scope

From: Date: Wed, 05 May 2010 17:02:53 +0000
Subject: note 97735 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-168980@lists.php.net to get a copy of this message
@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 />"; ?> ---- Server IP: 69.147.83.197 Probable Submitter: 216.94.129.143 ---- Manual Page -- http://www.php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/97735 Del: integrated -- https://master.php.net/note/delete/97735/integrated Del: useless -- https://master.php.net/note/delete/97735/useless Del: bad code -- https://master.php.net/note/delete/97735/bad+code Del: spam -- https://master.php.net/note/delete/97735/spam Del: non-english -- https://master.php.net/note/delete/97735/non-english Del: in docs -- https://master.php.net/note/delete/97735/in+docs Del: other reasons-- https://master.php.net/note/delete/97735 Reject -- https://master.php.net/note/reject/97735 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168980) next »