Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!news2.arglkargh.de!news.swapon.de!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: Mon, 17 Feb 2014 06:35:38 +0100 Lines: 54 Message-ID: References: <1816957.0LDT0NebiR@PointedEars.de> <0.9da5fd4e321b89e9adc3.20140216202439GMT.877g8u7qm0.fsf@bsb.me.uk> <0.1d3b7c8128d5ae4333af.20140216205119GMT.87siri6at4.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 QJ3udWgK6D2QeHdjUviLSg/5CdBoLRwKIO/0tthObJAqjiL4JT Cancel-Lock: sha1:7JV/pubsybuFOSNhkdEmW6UvBY0= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.2.0 In-Reply-To: <0.1d3b7c8128d5ae4333af.20140216205119GMT.87siri6at4.fsf@bsb.me.uk> Xref: csiph.com comp.lang.php:12857 On 16/02/14 21:51, Ben Bacarisse wrote: > "J.O. Aho" writes: > >> 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. > > Yes, though the question was rhetorical! Even if your question is rhetorical: One of the send guys did release an pdf some year ago where he wes recommending to strpos check before use of str_replace saying just that the strpos was more optimized. -- //Aho