Skip to content

Instantly share code, notes, and snippets.

@colshrapnel
Created August 5, 2022 17:48
Show Gist options
  • Select an option

  • Save colshrapnel/17b54f56e2ae06890a317b817f0b727d to your computer and use it in GitHub Desktop.

Select an option

Save colshrapnel/17b54f56e2ae06890a317b817f0b727d to your computer and use it in GitHub Desktop.
Measuring array_column+array_search vs. foreach
<?php
$size = 10000;
$a = [];
for ($i = 0; $i < $size; $i++) {
$a[] = ['uid' => $i, 'name' => 'Sandra Shush'.$i, 'pic_square' => 'urlof'.$i];
}
shuffle($a);
$count = 1000;
$t = microtime(1);
for ($i = 0; $i < $count; $i++) {
$needle = rand(0, $size-1);
foreach ($a as $key => $val) {
if ($val['uid'] === $needle) {
$id = $key;
break;
}
}
}
echo "loop: ".(round(microtime(1)-$t,4))."\n";
$t = microtime(1);
for ($i = 0; $i < $count; $i++) {
$needle = rand(0, $size-1);
$id = array_search($needle, array_column($a, 'uid'));
}
echo "sugar: ".(round(microtime(1)-$t,4))."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment