|
Posted by Rami Elomaa on 05/12/07 06:15
Mike P2 kirjoitti:
> I don't understand what's wrong with:
>
> if( trim( $variable ) == '' )
In php TIMTOWTDI (There Is More Than One Way To Do It). It's good to
know all the alternative ways of doing something and then choose the one
that best suits your needs.
> I just benchmarked it, it's faster than the regex methods.
With 100000 iterations using your (slightly modified) test script I also
got results that would indicate trim is actually faster, and it's no
wonder. Trim is a single purpouse function while a regex function has
far more functionality. In this case, since trim does exactly what needs
to be accomplished, it should be faster.
Now then, the results I got. For trim and 100000 iterations, I got ~ 0.4
secs, while the regex with the same amount of iterations took ~0.8 secs,
approximately twice as long. Just for fun, I also tested with much
longer strings, using these as input:
$t1 = str_repeat(' ',1000) . 'asdfasdf';
$t2 = str_repeat(' ',1000);
The result with 10000 iterations and /^\s*$/:
trim: 0.107841
regex: 3.455793
The longer the string is, the slower the regexp gets compared to trim.
It would seem that preg_match is O(n²) while trim is O(n).
Benchmarking is a good way to compare one way to another and I must
admit that trim in this case turned out faster. As to other qualities,
readability is one, but also, can it be modified? If the purpouse is to
test that user has given meaningful input, testing for spaces might not
be enough, there are other unmeaningful characters as well, such as
+-,.?!"£# etc, which trim will pass... Without knowing what the OP
actually needs this test for, I can't decide which is better, but if it
is only for testing that a string contains nothing but whitespace, then
in that case trim might be optimal.
--
Rami.Elomaa@gmail.com
"Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze
Navigation:
[Reply to this message]
|