markuszeller

Static Lookup Table Benchmark

Feb 20th, 2021 (edited)
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. <?php
  2.  
  3. // benchmarking lookup tables
  4. // static vs non-static
  5.  
  6. // PHP8.0 results are faster with static
  7.  
  8. for($j = 1; $j <= 10; $j++) {
  9.     echo "Pass $j", PHP_EOL;
  10.     $start    = microtime(true);
  11.     $startMem = memory_get_usage(true);
  12.     for ($i = 0; $i < 1e7; $i++) {
  13.         $test = search('two');
  14.     }
  15.     $end    = microtime(true);
  16.     $endMem = memory_get_usage(true);
  17.     echo $end - $start, '  ', $endMem - $startMem, PHP_EOL;
  18.  
  19.     $start    = microtime(true);
  20.     $startMem = memory_get_usage(true);
  21.     for ($i = 0; $i < 1e7; $i++) {
  22.         $test = searchStatic('two');
  23.     }
  24.     $end    = microtime(true);
  25.     $endMem = memory_get_usage(true);
  26.     echo $end - $start, '  ', $endMem - $startMem, PHP_EOL;
  27. }
  28.  
  29. function search($value): string {
  30.     $table = [
  31.         'one' => 'way',
  32.         'two' => 'ways',
  33.     ];
  34.  
  35.     return $table[$value] ?? '';
  36. }
  37.  
  38. function searchStatic($value): string {
  39.     static $table = [
  40.         'one' => 'way',
  41.         'two' => 'ways',
  42.     ];
  43.  
  44.     return $table[$value] ?? '';
  45. }
  46.  
Add Comment
Please, Sign In to add comment