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:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.