Advertisement
Guest User

IF vs SHORT IF

a guest
Aug 6th, 2015
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.52 KB | None | 0 0
  1. <?php
  2. /* How many times the code under test should run in each function */
  3. define('LOOP', 10000);
  4.  
  5. function f1()
  6. {
  7.     $data = range(0, LOOP);
  8.    
  9.     for ($value = null, $i = 0; $i < LOOP; ++$i) {
  10.         if (in_array($i, $data, true)) {
  11.             $value = $i;
  12.         } else {
  13.             $value = null;
  14.         }
  15.     }
  16. }
  17.  
  18. function f2()
  19. {  
  20.     $data = range(0, LOOP);
  21.    
  22.     for ($value = null, $i = 0; $i < LOOP; ++$i) {
  23.         $value = in_array($i, $data, true) ? $i : null;
  24.     }
  25. }
  26.  
  27. $start = microtime(true);
  28. f2();
  29. echo "\nSHORT: ".(microtime(true) - $start).' - MEMORY: '.memory_get_usage().' - MEMORY PEAK: '.memory_get_peak_usage();
  30.  
  31. $start = microtime(true);
  32. f1();
  33. echo "\nLARGE: ".(microtime(true) - $start).' - MEMORY: '.memory_get_usage().' - MEMORY PEAK: '.memory_get_peak_usage();
  34.  
  35. echo "\n\n";
  36.  
  37. ➜  microoptimizations  php -v
  38. PHP 5.6.4-4ubuntu6.2 (cli) (built: Jul  2 2015 15:29:28)
  39. Copyright (c) 1997-2014 The PHP Group
  40. Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
  41.     with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
  42.     with Xdebug v2.2.6, Copyright (c) 2002-2014, by Derick Rethans
  43.  
  44. ➜  microoptimizations  php if-vs-shortif.php
  45.  
  46. LARGE: 0.35390591621399 - MEMORY: 240720 - MEMORY PEAK: 1734208
  47. SHORT: 0.33055996894836 - MEMORY: 240816 - MEMORY PEAK: 1734632
  48.  
  49. ➜  microoptimizations  php if-vs-shortif.php
  50.  
  51. SHORT: 0.32460117340088 - MEMORY: 240720 - MEMORY PEAK: 1734208
  52. LARGE: 0.328537940979 - MEMORY: 240816 - MEMORY PEAK: 1734632
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement