Created
April 16, 2014 14:10
-
-
Save Camwyn/10881881 to your computer and use it in GitHub Desktop.
Test for multi-dimensional array search optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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