这里我有2个方法str_replace用于替换给定短语中的字符串.
// 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);
Run Code Online (Sandbox Code Playgroud)
哪种方法更有效(在使用的执行时间和资源方面)?
假设真正的短语更长(例如50,000个字符),并且要替换的单词具有更多对.
我的想法是方法2调用str_replace3次,这将花费更多的函数调用; 另一方面,方法1创建2个数组,并且str_replace需要在运行时解析2个数组.
我更喜欢使用方法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";
?>
Run Code Online (Sandbox Code Playgroud)
测试1(3.6321988105774秒)
测试2(2.8234610557556秒)
<?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";
?>
Run Code Online (Sandbox Code Playgroud)
测试1中(1.1450328826904秒)
测试2(1.3119208812714秒)
| 归档时间: |
|
| 查看次数: |
9480 次 |
| 最近记录: |