PHP: optimizing the use of Arrays
Write programs in PHP is very easy, that is because PHP syntax is simple and very effective. But also in PHP you must have some concepts for write effective programs, because if you are planing to have a very busy web site that little optimizations tips could help you to handle more visitors and to offload a little the processor.
All test were done in a Intel III PC with GNU/Linux SuSE 10.2, 1GB of RAM memory. All these examples uses the following functions for measure the time of execution:
<?php function start() { global $t; $t = time() + (float)microtime(); } function _time($s) { global $t; $e = time() + (float)microtime(); return $s.($e-$t).“ seconds<br/>“; } ?>
Avoid the Array of Array
An array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages the array index is a number, but in PHP the key could be anything ( string, integers, floats), that is because PHP does an hash with the index. That is a great feature that can made easy develop flexible programs.
But also that feature could have an negative impact if we usually use “array of array”. Example:
<?php start(); for($i=0; $i < 60000; $i++) $f[‘a‘][‘b‘][$i] = $i; print _time(“Execution time: “); ?> Execution time: 0.07426404953 seconds
But sometimes it is necesary to use “array of array” for made the code simpler and more shorter. In this case is a good alternative to use reference to a variable.
<?php start(); $b = &$f[‘a‘][‘b‘]; for($i=0; $i < 60000; $i++) $b[$i] = $i; print _time(“Execution time: “); ?> Execution time: 0.0515649318695 seconds
Now we can see than the second string is faster than the first that is because in the first script PHP is doing three hash lookups for every new itineration of the for, and in the second the first time the two lookups are done and save that refence in $b, so in the for only one lookup is done instaed of three.
Do never use array with undeclarated constants
PHP will process $f[a],”a” as a constanst and if “a” is not a constant PHP will process as $f[’a'].
<?php start(); for($i=0; $i < 60000; $i++) $f[a] = $i; print _time(“Execution time: “); ?> Execution time: 0.23406291008 seconds
Sould be:
<?php start(); for($i=0; $i < 60000; $i++) $f[‘a‘] = $i; print _time(“Execution time: “); ?> Execution time: 0.0413820743561 seconds
As we can see the difference in time execution is very big, the seconds script execute almost 6 times faster than the first, and the only difference are the quotes (singles or double are the same). That is becuase in the first the Index a is a constant and in run-time PHP do an lookup in constants-table and do not find, so then transform that constant into a string.
Loops with arrays
<?php $array= range( 1, 10000); start(); for($i=0; $i < count($array); $i++) ; print _time(“Execution time: “); ?> Execution time: 0.0144419670105 seconds
<?php $array= range( 1, 10000); start(); $b = count($array); for($i=0; $i < $b; $i++) ; print _time(“Execution time: “); ?> Execution time: 0.00201916694641 seconds
<?php $array= range( 1, 10000); start(); foreach($array as $k => $v); ; print _time(“Execution time: “); ?> Execution time: 0.00279021263123 seconds
We can see that the fist script has lowest perfomance that is because for every itineration the for is calling the “count” function and is counting the lenght of the array. In the second script the “count” is calling only one time and save in $b, that is the fasted solution because usually arrays do not change their length on loops. And the third function has higher time executing than the second and lowest than the first but it is the best (i think) for itinerate arrays with non-numerical index.
Do you know other tips?
Please let us know, write down your own tips!
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.
September 30th, 2007 at 8:26 am
There are some big difference there so your results may well be valid but I have very little faith in the benchmarks. I’ve actually covered this on my blog only recently.
http://torrentialwebdev.com/blog/archives/118-Better-Benchmarks.html
Also, I haven’t seen a timing function created like that before. Is there a reason why you didn’t use microtime(TRUE) or was it just personal preference?
p.s. Your comment form is nasty. This is the second, and far less detailed, comment I’ve written because the first attempt was lost when I got the CAPTCHA wrong.
September 30th, 2007 at 2:34 pm
its a nice tutorial about arrays.I had no idea earlier arrays having this much of disadvantages if we use wrongly
Thanks
www.w3answers.com
November 12th, 2007 at 8:25 am
Thank you for remember this, if every coder use this philosohpy then we can understand and reuse almost every single program we found in PHP source.
I have encountered several webpages sourcecode which i had to re-edit and get them work as spected so many times,…with a bad code… :O
i going to re-publish what you have said
November 28th, 2007 at 8:38 pm
for good coding purposes set the error_reporting to E_ALL and you probably would have catched the third example. (it would have given a warning about use a an assumed constant etc…)
another (good) benchmark done: http://www.php.lt/benchmark/phpbench.php (quite usefull)
and one last funny tip: $i++ is slower than ++$i
Good luck!
December 13th, 2007 at 8:25 am
Hello,
I have subscribed your feeds! I very like your blog. Congratulations!
I have one question. What plugin you are using to highlight the php codes?
May you reply my question, please?
Thank you!
December 13th, 2007 at 12:11 pm
Hello Marcus
Thank you for posting in my blog, I want to tell you that this blog will not be exclusive about PHP, I’ll write here about networks and others things too, my php-blog is www.thyphp.com you in your feeds too.
Also you see http://code.cesarodas.com/ which is my public repository of php-codes.
And about your question, I don’t user a plug, if you find one please let me know ;). Actually I copy all the output of “highlight_string” function in PHP (http://www.php.net/highlight_string).
Regards!
January 31st, 2008 at 2:29 pm
Hey cesar, well…like Marcus, im going to beg you for something….
have you used Zend Framework ? pls! im getting crazy with this thing…
ALl time i had been against this type of aplications, but now, i must learn it, because of work…but most tutorials out there are for phpseniors or something…
im just an intermediate php programmer, so, thats why im asking you this,…pls if u have the time, check it out, its zend framework….
maybe a good step by step y en español estaria perfecto, pues no hay absolutamente nada bueno en español que te enseñe el camino.
thanks and sorry for writting spanish, hehe
hope you have the time for this