Here I have 2 methods using str_replace
to replace strings in a given phrase.
// Method 1
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$phrase = str_replace($healthy, $yummy, $phrase);
// Method 2
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
Which method is more efficient (in terms of execution time & resources used)?
Assume the real phrase is much longer (e.g. 50,000 characters), and the words to replace have a lot more pairs.
What I am thinking is that Method 2 calls str_replace
3 times, which will cost more function calls; on the other hand Method 1 create 2 arrays, and the str_replace
needs to parse 2 arrays in runtime.
I would prefer to use method 1 as its cleaner and more organised also Method 1 gives opportunity to use pairs from other source eg: bad words table in database. Method 2 would require another loop of sort..
<?php
$time_start = microtime(true);
for($i=0;$i<=1000000;$i++){
// Method 1
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for($i=0;$i<=1000000;$i++){
// Method2
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (3.6321988105774 seconds)
Did Test 2 in (2.8234610557556 seconds)
<?php
$phrase = str_repeat("You should eat fruits, vegetables, and fiber every day.",50000);
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$time_start = microtime(true);
for($i=0;$i<=10;$i++){
// Method 1
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for($i=0;$i<=10;$i++){
// Method2
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (1.1450328826904 seconds)
Did Test 2 in (1.3119208812714 seconds)