PHP Performance Optimization on Functions and Constructs
Here are some performance/optimization tips, tricks and best practices to keep in mind when developing in PHP.
The list will be updated on a regular basis, so check back for updates
Functions & Constructs
• Use echo instead of print(); as echo is a language construct and print is a function.
• Use echo with commas and not dots/periods (concatenation); The theory is that commas will save PHP from string concatenation and would therefore be slightly faster, however there are some contradicting opinions about this one.
• Magic variables and magic methods are expensive. However, good use of these magic methods will render the performance degradation insignificant. Personally I like using __set() and __get() as it gives a lot of power and convenience.
• include_once() and require_once() is more expensive than include() and require(); Logical really, as the system will need to check if you have previously included/required that file before. Unavoidable in many situations, however a reminder to not use the _once() functions unnecessarily.
• switch/case statements are faster than elseif statements; and they are also more legible and easier to maintain. However there are situations when elseif statements may be preferred.
• Global variables are slow; even if they are defined but not used. Avoid unnecessary global variables where possible.
• Avoid function calls and tests inside loop constructs; this is a common tip and most people should know it, but putting function calls inside loop constructs such as for($i=0;$i($somevar);$i++)>
• Accessing $_SERVER['REQUEST_TIME'] is faster than the conventional time() function call; however only available in PHP5+.
• Explore and use predefined PHP functions before writing your own; this is a time-saver and often more efficient than re-inventing the wheel.
Comments 0