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.

 

Next chapter: Compress your output >>

Previous chapter: Keep up to date

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar