note 95033 deleted from function.ctype-digit by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 15:57:21 +0000 |
| Subject: | note 95033 deleted from function.ctype-digit by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189885@lists.php.net to get a copy of this message | ||
Note Submitter: walter
----
I was looking at whether this would save time on the numerous input validations I make in legions of
scripts. Typically I use a function numbers_only() which simply does a preg_replace() to remove
non-digits from a string.
To test for a possible speedup, I created a new function which only performed the preg_replace()
once a type_digit() check had failed.
The results for 1 million interations showed that using ctype_digit() beforehand caused
approximately 1/3rd additional latency on strings that were going to be preg_replace()'d anyway
(ie: strings that did not contain only digits). It caused an over 100% speedup over that (latency
inclusive) time for input strings that were pure numbers. The speedup was around 2/3 of the
original blind preg_replace().
The lesson for me is that it's only worth trying to optimise away preg_replace() using
ctype_digit() or similar if you know with some certainty that the vast majority of your inputs will
lean one way or the other.
Having said that, ctype_digit() seems to be cosnistently 30% faster than preg_match(). But adding
the additional PHP option as a requirement for your codebase may not justify the optimisation.
Let's face it: PHP aint exactly assembler, even if it is much faster than ruby :)