2013-04-16 70 views
-4

我有一個字符串,由用戶輸入。它可以同時具有大寫字母和非大寫字母。看看這個例子:在這種特殊情況下哪個更快?

<?php 
$var='This is a Text for A TEST'; // string, entered by the user 

//Situation 1 
$var=str_ireplace(' a ', ' ', $var); // I want to remove every 'a' as a word in the string and replace it with a single space 
// It will replace both the capitalized and non-capitalized A's in the string, because the function is 'ireplace' 
$var=strtolower($var); // I want all the letters to be non-capitalized 
echo $var; // print out the string 

//Situation 2 
$var=strtolower($var); // First make the letters non-capitalized 
$var=str_replace(' a ', ' ', $var); // Then replace all the A's in the string, which will be already non-capitalized 
echo $var; // print out the string 
?> 

這兩種情況做同樣的事情,但哪一個更快?

編輯:在提出關於php性能的問題之前,應該總是先跟蹤時間,然後如果不太確定哪種方法更快,可以在Stackoverflow上提問。

編輯2:從4月16日起,我一直在跟蹤自己的時間,並獲得更適合我的表現結果。我的建議總是在詢問之前檢查。

+4

爲什麼不試試看看? –

+0

那時候我沒有進行性能測試,但現在我做了。所以測試方法不再是我自己測試方法的問題。 – thexpand

+0

我喜歡「編輯2」!這應該是一個引號'總是詢問'之前檢查 –

回答

0

測試表明第二個速度快了大約25%。

function timer($timeOnly = FALSE) 
{ 
    static $startTime = null; 

    if($startTime === null) 
    { 
     $startTime = array_sum(explode(" ", microtime())); 
    } 
    else 
    { 
     $endTime = array_sum(explode(" ", microtime())); 
     $totalTime = ($endTime - $startTime); 
     $startTime = NULL; 

     return ($timeOnly) ? $totalTime : 'Time taken: '.$totalTime; 
    } 
} 

     $var = 'This is a Text for A TEST Aaaa AbbA'; // string, entered by the user 
     //Situation 1 
     timer(); 
     for($index = 0; $index < 1000000; $index++) 
     { 
      $var = str_ireplace(' a ', ' ', $var); // I want to remove every 'a' as a word in the string and replace it with a single space 
      // It will replace both the capitalized and non-capitalized A's in the string, because the function is 'ireplace' 
      $var = strtolower($var); // I want all the letters to be non-capitalized 
     } 
     echo timer(); 

     //Situation 2 
     timer(); 
     for($index = 0; $index < 1000000; $index++) 
     { 
      $var = strtolower($var); // First make the letters non-capitalized 
      $var = str_replace(' a ', ' ', $var); // Then replace all the A's in the string, which will be already non-capitalized 
     } 
     echo timer(); 
0
Situation 1: 10.70276 seconds for 10^7 iterations 
Situation 2: 9.08388 seconds for 10^7 iterations 

好像第二更快(自然的,因爲它必須搜索較少可能的字母(小寫只))。 (如果字符串大小會被str_ireplace大幅降低,第一個速度將會更快)