2011-09-24 63 views
4

我的問題是,如果在str_replace上使用數組比執行多次更快。我的問題只有兩個替代。數組str_replace速度更快嗎?

隨着陣列

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

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

每個搜索詞一旦

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

$newphrase = str_replace("vegetables", "beer", $phrase); 
+5

可能。但差別可能是無法估量的。 (在你的平臺上測量一個特定的答案) –

+4

http://c2.com/cgi/wiki?PrematureOptimization – Amber

+3

最快的解決方案是簡單地從代碼開始:'$ phrase =「你應該吃披薩,啤酒和纖維每天。「;' –

回答

1

PHP Docsstr_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; 

來看,PHP是每個$search陣列節點應用str_replace所以您的兩個例子,與在性能方面卻一定要使用搜索數組而替換更具可讀性和未來教授性,因爲您可以在將來輕鬆更改陣列。

+1

是的,如果你的數組不好,你可以在索引上給它一個耳光,使它成爲一個好小男孩...... ;-) – 2011-09-24 05:47:51

0

我不知道,如果它的速度更快,但我傾向於做的陣列路線走,因爲它更易於維護和可讀性給我。 ..

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

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

如果我不得不猜測我會說多次調用str_replace會很慢呃但我不確定str_replace的內部結構。有了這樣的東西,我傾向於可讀性/可維護性,因爲優化的好處根本不存在,因爲根據替換次數的不同,您可能只能獲得大約0.0005秒的差異。

如果您真的想要找出時差,那麼在沒有建立休眠數據集的情況下,爲了達到您可以看到實際時差與測試混淆中的異常之間的差距,幾乎是不可能的。

使用這樣的事情...

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

......將讓你的時間的請求。

+0

祕密提示:'strtr($ old_str,$ replace)':) – NikiC

+0

不錯,謝謝你的提示=) –

-1

嘗試在每次不同的方法使用後,這一點,你很快就會看到是否有轉速差:

echo microtime()