Advertisement
adrenalinkin

sprintf vs concat vs inline

Jan 20th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.99 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. // SET UP
  6.  
  7. $iterations = 1000000;
  8. $x = 'Custom Text';
  9.  
  10. $actions = array(
  11.     "sprintf" => function () use ($x) {
  12.         return sprintf('There some string: %s', $x);
  13.     },
  14.     "concat" => function () use ($x) {
  15.         return 'There some string: '. $x;
  16.     },
  17.     "inline" => function () use ($x) {
  18.         return 'There some string: $x';
  19.     },
  20. );
  21.  
  22. // --------------------------------
  23.  
  24. function benchmark($name, $iterations, $action)
  25. {
  26.     $startMemory = memory_get_usage(true);
  27.     $startTime = microtime(true);
  28.  
  29.     for ($i = 0; $i <= $iterations; ++$i) {
  30.         $a = $action();
  31.     }
  32.  
  33.     $endTime = microtime(true);
  34.     $endMemory = memory_get_usage(true);
  35.  
  36.     echo sprintf(
  37.         'T: %.6f | M: %.2f | %s' . PHP_EOL,
  38.         round($endTime - $startTime, 6),
  39.         round($endMemory - $startMemory, 2),
  40.         $name
  41.     );
  42. }
  43.  
  44. echo '<pre>' . PHP_EOL;
  45.  
  46. foreach ($actions as $name => $action) {
  47.     benchmark($name, $iterations, $action);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement