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

  1. <?php
  2. /**
  3. * It's hard to believe this isn't a PHP builtin.
  4. *
  5. * @param $source array to pull a subset of key/value pairs out of
  6. * @param $keys list of keys to pull out
  7. * @return $result array
  8. */
  9. function array_subset_of_the_array_based_on_a_list_of_keys (array $source, array $keys)
  10. {
  11. $result = array();
  12. foreach ($keys as &$key)
  13. $result[$key] = $source[$key];
  14. return $result;
  15. }
  16. function faster_version (array $source, array $keys)
  17. {
  18. $result = array();
  19. for ($i = 0, $size = count($keys); $i < $size; ++$i) {
  20. $key = $keys[$i];
  21. $result[ $key ] = $source[ $key ];
  22. }
  23. return $result;
  24. }
  25. $keys = array('one', 'two', 'three', 'four', 'five', 'six');
  26. $source = array(
  27. 'one' => 'blakdlajsfdlkajfds;lasjkflaksjf',
  28. 'two' => 'asdfkljasfkjsadfas;jdfas ldfjk',
  29. 'three' => 'alk;sjdfasklfjaslf;ja',
  30. 'four' => '6',
  31. 'five' => 2,
  32. 'six' => 12314
  33. );
  34. $start = microtime(true);
  35. for ($i = 0, $size = 100000; $i < $size; ++$i) {
  36. $pulled = faster_version($source, array('one', 'three', 'five'));
  37. }
  38. $time1 = microtime(true) - $start;
  39. $start = microtime(true);
  40. for ($i = 0, $size = 100000; $i < $size; ++$i) {
  41. $pulled = array_subset_of_the_array_based_on_a_list_of_keys($source, array('one', 'three', 'five'));
  42. }
  43. $time2 = microtime(true) - $start;
  44. echo "time1: $time1\ntime2: $time2\n";