Я бы предпочел использовать метод 1 в качестве более чистого и более организованного, а также метод 1 дает возможность использовать пары из другого источника, например таблицы плохих слов в базе данных. Метод 2 потребует еще один цикл сортировки ..
<?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";
?>
Пройти тест 1 дюйм (3,6321988105774 секунд)
Тест 2 в (2,8234610557556 секунд)
Редактировать: При дальнейшей проверке строки, повторяющейся до 50 Кб, меньше итераций и советов от ajreal, разница настолько мала.
<?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";
?>
Пройти тест 1 дюйм (1,1450328826904 секунды)
Пройти тест 2 в (1,3119208812714 секунд)