PHP optimizationbased on many information found on the internet and onpersonal experienceby Fabrizio Parrella
How where the tests performedThose tests have been made and repeated multipletimes then the values have been averaged andthe outliers removed. Your script/server mightgive you different results, this might be becauseyour CPU/memory/internal process/PHP GarbageCollector/etc... might interfere
String OutputIs there a difference between “echo” and “print” ?“echo” and “print” serve the same exact purpose.Various tests show that “echo” is about 10-15%faster when using comma separated items.
Variable Type Checkingisset() vs. empty() vs is_array()Often we need to check if a variable is set, so whatis the faster ?isset() and empty() are pretty much identicalis_array() takes twice as long
Quotes“ vs. Lots of information on the web about quotes.. whichis faster ?In the past there were some minor performancedifferences between “ and for a string thatdoesnt contain variables.In todays versions of PHP looks like that theargument has been satisfied on both sides asthey are pretty much the same
Counting Loopsfor vs. whileWhile or For.. For or While ? Many tests have beendone and many results have been posted all overthe internet.In reality, there is not enough difference in executionto make any very impact in the execution of theapplication.Micro-optimizing ?The “while” is about 13% faster on an empty loopthat counts up to 1,000,000
Read Loopsforeach vs. for vs. while(list() = each())This test is very tested like the “Counting Loops”and there are various results around.In my experience and the most commonly resultsfrom other tests is that “foreach()” without $key isthe winner. The next closest is the “for()” and thelast is the “while()”.If you must use the “while()” do not forget to use “reset()” first toincredibly speed up the process.“reset()” is good to use anytime you do a loop to reposition the pointer to the beginning
Control Structuresswitch/case/default vs. if/elseif/elseThere is no real difference between “switch” and “if”There is a difference is the equality sign, where ===is about 10% faster than ==
Counting LoopsFor-Loop tests – calculate size in advanceUnsurprising results, calculate the size of the loopahead of time for a 1000x repetitions is incrediblyfaster:test timePre-calc - count() 243µsNo pre-calc - count() 109,472µsPre-calc - sifeOf() 200µsNo pre-calc - sizeOf() 104,085µs
Modify Loopforeach() vs. for vs. while(list() = each())Often happens that you need to modify the arraywhile you are looping it, when doing so it is bestnot to loop the the array while modifying ittest timeforeach($array as $k=>$v) $array[$k] = value; 362µswhile(list($k) = each($array)) $array[$k] = value; 165µs$ks = array_keys($array);$size = count($k);for($i=0; $i<=$size; $i++) $array[$ks[$i]] = value;72µs
Got Perfect Code ?so you wrote perfect code, but you want it to go fasterHave you ever heard of OPCODE caching?
What is OPCODE caching?When a PHP script is called by a user:●User Requests the Page●Web Server Compiles the PHP script (interprets)●Executes the Compiled Version of the Page●Output the DataNormal Applications do not need to be compiled as they are often pre-compiled,however scripting languages like PHP, Perl, Ruby, etc., are compiled on demandand interpreted. (there is a difference between compiling and interpreting, but thatis for another time).As you can imagine, converting source code into machine code (opcode) can beresource intensive. Opcode caches will store opcode in a cache and execute isfrom there instead than constantly recompiling the code. This basically eliminatethe second step and seriously speed up the site.
It is Worth ?You know what it is.. but is it worth to spend time installing it ?Online research showed me that websites hadimprovements between 200% and 700%.My personal experience showed me a time savingof 120%.For example a page that before OPCode cachingtook 10 µs to load, with APC installed it took 4µs.
The Best OPCode cacheeAccellerator, APC, Xcache, ionCube, Turck MMCache, Zend, etc..There are MANY different OPCode cache that canbe installed for PHP, some are new, and someare well seasoned.My favorite are the ones that use shared memory toreduce slow disk accesses.I have tested different ones, my current favorite isAPC with PHP 5.3
BEST OPTIMIZATION?Done all of this but PHP is still slow ?You can optimize your PHP code and installOPCode cache but if you still have issues you cancheck the followings:●Database Queries●Disk accesses (fopen, dir, etc.)●Network (DNS, open on URLs, etc.)●Memory usage (memory_get_usage, memory_get_peak_usage)●Modules Installed●Endless Loops, Bugs