Cache array data
Do not ever repeatedly access the same element in an array unless you absolutely have to. Try running the following code on your own machine:
<?php
$START = time();
$foo['bar'] = "test";
for ($i = 0; $i < 10000000; ++$i) {
if ($foo['bar'] == "test") {
$j = 0;
}
}
$END = time() - $START;
print "Array took $END seconds\n";
$START = time();
$testvar = $foo['bar'];
for ($i = 0; $i < 10000000; ++$i) {
if ($testvar == "test") {
$j = 0;
}
}
$END = time() - $START;
print "Var took $END seconds\n";
?>
Running that took 38 seconds for the repeated array access, and 32 seconds for using a variable - the reason for this is that accessing array elements time and time again requires PHP to find the element inside the array, which is comparatively slow.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Compress your output >>
Previous chapter: Keep up to date
Jump to: Performance Optimising your code Write your code sensibly Use your tools wisely Use some functions carefully for maximum performance Use the Zend Optimizer for older PHP versions Use a PHP code cache for newer PHP versions Read the manual carefully Get your loops right first Pre-increment and post-increment aren't the same Don't think that using references will lower your RAM usage Be wary of garbage collection, part 1 Be wary of garbage collection, part 2 Listen to all errors, big and small Keep up to date Cache array data Compress your output Don't use CGI Don't use dl() Debug your code Cache your data with memcache Use persistent connections Take advantage of new features Compile right Ignore the myths Avoid mod_access if you can Make sure you optimize Apache Optimising your SQL Prioritise your data Optimise your tables Select as little data as possible Use shorter queries where possible Use the EXPLAIN statement Change your hardware Choose your data types carefully Size vs. Speed Declare fields NOT NULL Load data intelligently Consider splitting off variable-length fields Be wary of locks Consider switching OS Spot slow queries Perform joins carefully Index your data Make sure your indexes are being used Normalisation Upgrade MySQL Increase your buffers Keep tabs on your server Lock your tables when appropriate Don't rely on automatic type conversion Benchmark, benchmark, benchmark! Know MySQL's strengths Server PHP Accelerators Caching PHP PHP as a CGI or a module? Size of scripts Summary Exercises Further reading Next chapter
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws .