5

My question is if using array on str_replace is faster than doing it multiple times. My question goes for only two replaces.

With array

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables");
$yummy   = array("pizza", "beer");

$newphrase = str_replace($healthy, $yummy, $phrase);

each search word once

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$newphrase = str_replace("fruits", "pizza", $phrase);

$newphrase = str_replace("vegetables", "beer", $phrase);
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179

3 Answers3

1

From PHP Docs on str_replace :

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;

Looking at those examples, PHP is applying the str_replace for each $search array node so both of your examples are the same in terms of performance however sure using an array for search and replace is more readable and future-prof as you can easily alter the array in future.

  • 1
    Yes, if your array was going to be bad you can give it a little slap on the index and make it a good little boy... ;-) –  Sep 24 '11 at 05:47
0

I don't know if it's faster but I tend do go with the array route because it's more maintainable and readable to me...

$replace = array();
$replace['fruits']     = 'pizza';
$replace['vegetables'] = 'beer';

$new_str = str_replace(array_keys($replace), array_values($replace), $old_str);

If I had to guess I would say making multiple calls to str_replace would be slower but I'm not sure of the internals of str_replace. With stuff like this I've tended to go with readability/maintainability as the benefit to optimization is just not there as you might only get around 0.0005 seconds of difference depending on # of replacements.

If you really want to find out the time difference it's going to be close to impossible without building up a hugh dataset in order to get to the point where you can see an actual time difference vs anomalies from test confounds.

Using something like this ...

$start = microtime(true);
// Your Code To Benchmark
echo (microtime(true) - $start) . "Seconds"

... will allow you to time a request.

Daniel Doezema
  • 1,592
  • 10
  • 13
-1

Try using this before and after each different method and you will soon see if there is a speed difference:

echo microtime()
Dan
  • 2,073
  • 3
  • 22
  • 30