PHP 8.4.24 Released!

Voting

: five minus three?
(Example: nine)

The Note You're Voting On

bobvin at pillars dot net
15 years ago
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().

Here's a benchmark program to prove it:

<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
  $times['strncmp'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strncmp($haystack, $needle, 3) === 0;
  }
  $times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
  $times['strpos'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strpos($haystack, $needle) === 0;
  }
  $times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>

<< Back to user notes page

To Top