Re: strpos() before str_replace()? Or, maybe strtr()? [message #184922 is a reply to message #184918] |
Sun, 16 February 2014 14:15 |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 2/16/2014 4:49 AM, Jason C wrote:
> I know that I'm talking about microseconds here, so this is really just for the sake of furthering my own education.
>
> I'm looping through roughly 100,000 values:
>
> $userArr = array(
> "something" => "anything",
> ...
> );
>
> foreach ($userArr as $key => $val) {
> $firstname = str_replace($key, "****", $firstname);
> $lastname = str_replace($key, "****", $lastname);
> }
>
> Both $firstname AND $lastname could contain any of the keys, but could only potentially contain one key each. It's likely, though, that neither will contain any of the keys.
>
> Would it be faster to use strpos() before each str_replace(), like so?:
>
> foreach ($userArr as $key => $val) {
> if (strpos($firstname, $key) !== false)
> $firstname = str_replace($key, "****", $firstname);
>
> if (strpos($lastname, $key) !== false)
> $lastname = str_replace($key, "****", $lastname);
> }
>
> My instinct is that it would be the same, if not marginally slower; allowing a potential computation time for 100,002 strpos() as opposed to 100,000 str_replace().
>
> Or, would strtr() be faster? I've never actually used this function in practice; I think it's a slow function, but have never tested it, and don't remember where I read that:
>
> $firstname = strtr($firstname, $userArr);
> $lastname = strtr($lastname, $userArr);
>
> Any other suggestions on what might be the fastest option?
>
> TIA,
>
> Jason
>
The real question here is - what does it matter? Do you have a
performance problem? If so, what's the problem (I can about guarantee
it isn't here).
You can test it yourself, but that test is only going to be valid for
your current situation. Change versions of PHP, your OS or even the
means of calling PHP (i.e. CLI vs. Apache Module) may change the
results. And in this particular case, it will be highly dependent on
the data (i.e. the percentage of times your key appears in the strings).
You are much better off coding for clarity and testing. If you have a
performance problem, then is the time to find your performance problem
and fixing it. Donald Knuth had it right when he said "Premature
optimization is the root of all evil."
--
==================
Remove the "x" from my email address
Jerry Stuckle
jstucklex(at)attglobal(dot)net
==================
|
|
|