Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: "J.O. Aho" Newsgroups: comp.lang.php Subject: Re: strpos() before str_replace()? Or, maybe strtr()? Date: Sun, 16 Feb 2014 21:41:48 +0100 Lines: 42 Message-ID: References: <1816957.0LDT0NebiR@PointedEars.de> <0.9da5fd4e321b89e9adc3.20140216202439GMT.877g8u7qm0.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net BMjIGryxOBKKGPp0e0dU8QqJhpjrT4i5SND67fMPlFg91oXEbu Cancel-Lock: sha1:0TzxX6Q0MmkoaCYsgdLyiuJn2XE= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.2.0 In-Reply-To: <0.9da5fd4e321b89e9adc3.20140216202439GMT.877g8u7qm0.fsf@bsb.me.uk> Xref: csiph.com comp.lang.php:12848 On 16/02/14 21:24, Ben Bacarisse wrote: > Thomas 'PointedEars' Lahn writes: > >> Jason C wrote: > >>> 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); >>> } >> >> Most certainly not. > > And yet, when I measured it, it was faster. How can that be? > > For strpos is faster than str_replace on finding the string. -- //Aho