Created
September 19, 2022 15:52
-
-
Save seothemes/4fc29fc28479bb0bb381678d8b7a2aa5 to your computer and use it in GitHub Desktop.
modulo benchmark
This file contains hidden or 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 | |
$array = [ | |
0 => 'X', | |
1 => 'Y', | |
2 => 'Z', | |
3 => 'X', | |
4 => 'Y', | |
5 => 'Z', | |
6 => 'X', | |
7 => 'Y', | |
8 => 'Z', | |
9 => 'X', | |
10 => 'Y', | |
11 => 'Z', | |
]; | |
function get_value_from_pattern( $key, $pattern = [ 'X', 'Y', 'Z' ] ): string { | |
$array = []; | |
for ( $i = 0; $i < ( $key + 1 ) / count( $pattern ); $i++ ) { | |
$array = [ ...$array, ...$pattern ]; | |
} | |
return $array[ $key ] ?? ''; | |
} | |
function get_modulo_index_from_array( $array, $mod_index ) { | |
return $array[ $mod_index % count( $array ) ]; | |
} | |
function get_value_from_pattern_fill( $index, $pattern ) { | |
$array = array_merge( ...array_fill( 0, $index, $pattern ) ); | |
return $array[ $index ] ?? ''; | |
} | |
echo '<pre><code>'; | |
$start_time = microtime( true ); | |
for ( $i = 0; $i < 1000; $i++ ) { | |
get_modulo_index_from_array( $array, $i ); | |
} | |
$end_time = microtime( true ); | |
echo 'get_modulo_index_from_array: ' . ( $end_time - $start_time ) . '<br/>'; | |
$start_time = microtime( true ); | |
for ( $i = 0; $i < 1000; $i++ ) { | |
get_value_from_pattern( $i, $array ) . '<br/>'; | |
} | |
$end_time = microtime( true ); | |
echo 'get_value_from_pattern: ' . ( $end_time - $start_time ) . '<br/>'; | |
$start_time = microtime( true ); | |
for ( $i = 0; $i < 1000; $i++ ) { | |
get_value_from_pattern_fill( $i, $array ); | |
} | |
$end_time = microtime( true ); | |
echo 'get_value_from_pattern_fill: ' . ( $end_time - $start_time ) . '<br/>'; | |
echo '</pre></code>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment