這裏我有兩種方法使用str_replace
替換給定短語中的字符串。PHP中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);
哪種方法是更有效的(在執行時間方面使用&資源)?
假設實際的詞組要長得多(例如50,000個字符),並且要替換的詞有更多的對。
我在想什麼是方法2調用str_replace
3次,這將花費更多的函數調用;另一方面,方法1創建2個數組,而str_replace
需要在運行時解析2個數組。
方法1更快。 – djot
既不是一個好的選擇,如果你有一個很長的字符串,反覆需要str_replace,爲什麼不在str_replace之後保存結果呢? – ajreal
如果您在循環中一遍又一遍地創建ARRAYs healty和yummy,它會變慢,而不是將它們放在外面。 – djot