As a Sr. Web Programmer here at Noam Design, I always look for ways to optimize the code I develop for efficiency. I primarily do back-end programming with PHP and MySQL. Today I am going to share with you some tips that I have personally encountered while programming with PHP. I hope these 15 tips will help you optimize your PHP code and get you into the habit of looking for alternative ways or patterns of writing robust code. Also don’t forget to document your code properly! Enjoy!
- echo is faster than print.
- Wrap your string in single quotes (‘) instead of double quotes (“) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
- Use echo‘s multiple parameters (or stacked) instead of string concatenation.
- Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
- Unset or null your variables to free memory, especially large arrays.
- str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.
- else if statements are faster than select statements aka case/switch.
- Close your database connections when you’re done with them.
- $row['id'] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.
- Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.
- Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
- When using header(‘Location: ‘.$url); remember to follow it with an exit; as the script continues to run even though the location has changed or avoid using it all together where possible.
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
- Methods in derived classes run faster than ones defined in the base class.
- Error suppression with @ is very slow.
More to come!