[ create a new paste ] login | about

Link: http://codepad.org/x03lrEp7    [ raw code | output | fork ]

PHP, pasted on Nov 4:
<?php

function func1($haystack, $needle) {
      $len = strlen($needle);
      foreach ($haystack as $hay) {
          if (substr($hay, 0, $len) == $needle) {
              return true;
          }
      }
      return false;
  }

function func2($haystack, $needle) {
   foreach ($haystack as $hay) {
      if (strpos($hay, $needle) === 0) {
          return true;
      }
   }
   return false;
}

$c = 10000;
$n = 0;

$arr = array('Apple', 'Application');

$time1 = microtime(true);
while ($n++ < $c)
{
  func1($arr, 'App');
}
$time2 = microtime(true);

$time3 = microtime(true);
while ($n-- > 0)
{
  func2($arr, 'App');
}
$time4 = microtime(true);

echo 'Original function: ', ($time2-$time1), "\r\n";
echo 'With strpos(): ', ($time4-$time3);


Output:
1
2
Original function: 0.05633807182312
With strpos(): 0.054251909255981


Create a new paste based on this one


Comments: