18.1.14 Cache array dataThis is NOT the latest copy of this book; click here for the latest version.
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 see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|