Re: strpos() before str_replace()? Or, maybe strtr()? [message #184937 is a reply to message #184936] |
Mon, 17 February 2014 02:19 |
Ben Bacarisse
Messages: 82 Registered: November 2013
Karma:
|
Member |
|
|
Denis McMahon <denismfmcmahon(at)gmail(dot)com> writes:
<snip>
> Not sure whether something like this could be faster or not:
>
> foreach ( $userArr as $key => $val ) {
>
> if ( ( $f = strpos( $firstname, $key ) ) !== false )
> $firstname = substr( $firstname, 0, $f ) . "****" .
> substr( $firstname, $f + strlen( $key ) );
>
> if ( ( $l = strpos( $lastname, $key ) ) !== false )
> $lastname = substr( $lastname, 0, $l ) . "****" .
> substr( $lastname, $l + strlen( $key ) );
>
> }
>
> As I don't have representative data to test against.
Given the structure of the data (lots of tests, with rate matches) I'd
expect this to be much like the strpos + str_replace solution, since the
speed of determining that there is no match dominates. The assignment
to $l might have a small effect, and that seems to be the case. The
timings show it's a few percent slower than the plain strpos+str_replace
solution.
The situation is an odd one. Matches are very rare, and this makes it
worthwhile avoiding as much work as possible when there is no match.
The positions $f and $l are only needed when there is a match, so,
oddly, it makes sense to re-calculate them rather than to assign them
every time. I.e. this unlikely pattern:
if (strpos( $firstname, $key) !== false ) {
$f = strpos($firstname, $key);
$firstname = substr($firstname, 0, $f) . "****" .
substr($firstname, $f + strlen($key));
}
is faster than the above (but by a small, if consistent, amount).
Avoiding 99,999 assignments at the cost of maybe one strpos call is a
win (though I am sure you can construct data sets that reduce or
eliminate this advantage). When there is no match at all (which the OP
describes as a likely event), avoiding 100,000 assignments at the cost
of nothing, can't be anything but a win!
<snip>
--
Ben.
|
|
|