Skip to content

Instantly share code, notes, and snippets.

@Camwyn
Created April 16, 2014 14:10
Show Gist options
  • Save Camwyn/10881881 to your computer and use it in GitHub Desktop.
Save Camwyn/10881881 to your computer and use it in GitHub Desktop.
Test for multi-dimensional array search optimization
<?php
$loops = 1000000;
$index_array = array(
'Mr. Giggles' => 'first',
'Lucky Pete' => 'second',
'door' => 'third',
'bar' => 'fourth',
'Marius' => 'fifth',
);
$array = array(
'first' => array(
'type' => 'cat',
'name' => 'Mr. Giggles',
'age' => 3,
),
'second' => array(
'type' => 'dog',
'name' => 'Lucky Pete',
'age' => 2,
),
'third' => array(
'type' => 'door',
'name' => 'door',
'age' => 1,
),
'fourth' => array(
'type' => 'foo',
'name' => 'bar',
'age' => 'baz',
),
'fifth' => array(
'type' => 'giraffe',
'name' => 'Marius',
'age' => 7,
),
);
$start = microtime( TRUE );
for ( $i = 0; $i < $loops; $i++ )
{
foreach ( $array as $number => $item )
{
if ( 'bar' == $item['name'] )
{
$test = $number;
break;
}//end if
}//end foreach
}//end for
$total = microtime( TRUE ) - $start;
$avg = $total / $loops;
echo "Average for foreach with break: {$total}s ( {$avg}s per iteration)\n";
$start = microtime( TRUE );
for ( $i = 0; $i < $loops; $i++ )
{
while ( list( $number, $item ) = each( $array ) && empty( $test ) )
{
if ( 'bar' == $item['name'] )
{
$test = $number;
}//end if
}//end while
}//end for
$total = microtime( TRUE ) - $start;
$avg = $total / $loops;
echo "Average for while with conditional: {$total}s ( {$avg}s per iteration)\n";
$start = microtime( TRUE );
for ( $i = 0; $i < $loops; $i++ )
{
if ( isset( $index_array['bar'] ) )
{
$test = $array[ $index_array['bar'] ];
}//end if
}//end for
$total = microtime( TRUE ) - $start;
$avg = $total / $loops;
echo "Average for isset: {$total}s ( {$avg}s per iteration)\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment