Skip to content

Instantly share code, notes, and snippets.

@ibrasho
Last active August 29, 2015 14:06
Show Gist options
  • Save ibrasho/4108828ed52a7204074b to your computer and use it in GitHub Desktop.
Save ibrasho/4108828ed52a7204074b to your computer and use it in GitHub Desktop.
<?php
echo '<pre>';
// Setup input array
$input = [];
for ($i = 0; $i < 100000; $i++) {
$input[] = rand(~PHP_INT_MAX, PHP_INT_MAX);
}
$foreach_if_times = [];
$array_filter_times = [];
for ($i = 0; $i < 100; $i++) {
$start = microtime(true);
array_filter($input, function ($item) {
return ($item > 0);
});
$array_filter_times[] = microtime(true) - $start;
}
for ($i = 0; $i < 100; $i++) {
$start = microtime(true);
$result = [];
foreach ($input as $item) {
if ($item > 0) {
$result[] = $item;
}
}
$foreach_if_times[] = microtime(true) - $start;
}
echo sprintf("Avg time: %.8f\n", $array_filter_avg = array_sum($array_filter_times) / count($array_filter_times));
echo sprintf("Avg time: %.8f\n", $foreach_if_avg = array_sum($foreach_if_times) / count($foreach_if_times));
echo sprintf("Difference: %.8f\nRatio: %.8f\n", $array_filter_avg - $foreach_if_avg, $array_filter_avg / $foreach_if_avg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment