Skip to content

Instantly share code, notes, and snippets.

@vicb
Created January 11, 2012 20:25
Show Gist options
  • Save vicb/1596588 to your computer and use it in GitHub Desktop.
Save vicb/1596588 to your computer and use it in GitHub Desktop.
substr vs strpos
<?php
$str = str_repeat('*!', 10);
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
substr($str, 0, 1);
}
printf("substr took: %d\n", (microtime(true) - $start) * 1000);
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
strpos($str, '@');
}
printf("strpos took: %d\n", (microtime(true) - $start) * 1000);
@aaronbauman
Copy link

spoler alert: strpos is consistently faster.

@achasseux
Copy link

+1 substr vs strpos

@inpresif
Copy link

spoler alert: strpos is consistently faster.

On my end, after 10 checks and increased loops, it was the other way around by at least 1,5x

substr took: 85
strpos took: 129

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment