FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » strpos() before str_replace()? Or, maybe strtr()?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: strpos() before str_replace()? Or, maybe strtr()? [message #184937 is a reply to message #184936] Mon, 17 February 2014 02:19 Go to previous messageGo to previous message
Ben Bacarisse is currently offline  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.
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: getting php mail error info
Next Topic: Declaring an array necessary?
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Fri Oct 18 14:20:06 GMT 2024

Total time taken to generate the page: 0.04115 seconds