Dotfiles, utilities, and other apparatus.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

54 lines
1.3 KiB

<?php
/**
* It's hard to believe this isn't a PHP builtin.
*
* @param $source array to pull a subset of key/value pairs out of
* @param $keys list of keys to pull out
* @return $result array
*/
function array_subset_of_the_array_based_on_a_list_of_keys (array $source, array $keys)
{
$result = array();
foreach ($keys as &$key)
$result[$key] = $source[$key];
return $result;
}
function faster_version (array $source, array $keys)
{
$result = array();
for ($i = 0, $size = count($keys); $i < $size; ++$i) {
$key = $keys[$i];
$result[ $key ] = $source[ $key ];
}
return $result;
}
$keys = array('one', 'two', 'three', 'four', 'five', 'six');
$source = array(
'one' => 'blakdlajsfdlkajfds;lasjkflaksjf',
'two' => 'asdfkljasfkjsadfas;jdfas ldfjk',
'three' => 'alk;sjdfasklfjaslf;ja',
'four' => '6',
'five' => 2,
'six' => 12314
);
$start = microtime(true);
for ($i = 0, $size = 100000; $i < $size; ++$i) {
$pulled = faster_version($source, array('one', 'three', 'five'));
}
$time1 = microtime(true) - $start;
$start = microtime(true);
for ($i = 0, $size = 100000; $i < $size; ++$i) {
$pulled = array_subset_of_the_array_based_on_a_list_of_keys($source, array('one', 'three', 'five'));
}
$time2 = microtime(true) - $start;
echo "time1: $time1\ntime2: $time2\n";