Skip to content

Instantly share code, notes, and snippets.

@bor0
Last active May 31, 2023 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bor0/3fa539263335fa415faa67606a469f2e to your computer and use it in GitHub Desktop.
Save bor0/3fa539263335fa415faa67606a469f2e to your computer and use it in GitHub Desktop.
<?php
$start = microtime( true );
$book_sections = [ '1.0', '1.1', '1.2', '2.0', '2.1', '3.0', '3.1' ];
$groups = array_group_pair( $book_sections, function( $p1, $p2 ) {
return $p1[0] === $p2[0];
} );
$end = microtime( true );
printf( "%.10f\n", $end - $start );
<?php
$start = microtime( true );
$book_sections = [ '1.0', '1.1', '1.2', '2.0', '2.1', '3.0', '3.1' ];
function custom_array_group(array $arr1, callable $compare): array {
$groups = [];
$group = [];
$prev = NULL;
foreach ($arr1 as $value) {
if ($group && !$compare($prev, $value)) {
$groups[] = $group;
$group = [];
}
$group[] = $value;
$prev = $value;
}
if ($group) {
$groups[] = $group;
}
return $groups;
}
$groups = custom_array_group( $book_sections, function( $p1, $p2 ) {
return $p1[0] === $p2[0];
} );
$end = microtime( true );
printf( "%.10f\n", $end - $start );
@bor0
Copy link
Author

bor0 commented May 30, 2023

$ for i in {1..100}; do sapi/cli/php test_array_group_php.php; done | awk '{sum += $1} END {print sum/100}'
3.22533e-05
$ for i in {1..100}; do sapi/cli/php test_array_group_c.php; done | awk '{sum += $1} END {print sum/100}'
2.44975e-05

An improvement of (3.22533 - 2.44975)/3.22533 = 24%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment