Skip to content

Instantly share code, notes, and snippets.

@Fusselwurm
Created September 11, 2014 07:13
Show Gist options
  • Save Fusselwurm/36de5b0b28d22c04e19d to your computer and use it in GitHub Desktop.
Save Fusselwurm/36de5b0b28d22c04e19d to your computer and use it in GitHub Desktop.
Which is faster, regex or type casting, when deciding whether a string represents an integer?
<?php
$value = '0647№7№7№/0';
$time = microtime(true);
$loops = 100000;
$result = true;
for ($i = 0; $i < $loops; $i++) {
$result &= preg_match('/^[0-9]+$/', $value);
}
echo "\nwith preg_match: " . (microtime(true) - $time);
$time = microtime(true);
$result = true;
for ($i = 0; $i < $loops; $i++) {
$result &= ((string) (int) $value === $value);
}
echo "\nwith casting: " . (microtime(true) - $time);
echo "\n\n";
@Fusselwurm
Copy link
Author

selbst für strings mit 1 char ist casting 3mal so schnell

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