2010-03-07 48 views
1

下面的例程對輸入的超文本流進行兩次掃描。第一遍是用戶定義的短語選項的自旋替換。第二遍是在下面的doReplace函數中的標籤集合上進行查找替換。這個例程如何更好地優化?

我只是在尋找如何優化它的建議。我沒有任何性能問題。但我想要構建可擴展性。

/* FIND REPLACE SPIN 
--------------------------------------------------------------------*/ 
function doReplace($content) 
{ 
// content is a precompiled text document formatted with html and 
// special using replacement tags matching the $tags array collection below 
    $tags = array('[blog-name]', '[blog-url]', '[blog-email]'); 
    $replacements = array('value1', 'value2', 'value3'); 
    $content = str_replace($tags, $replacements, $content); 
    return $content; 
} 

function doSpin($content) { 
// the content also has phrase option tags denoted by [%phrase1|phrase2_|phrase3%] 
// delimiters throughout the text. 
    return preg_replace_callback('!\[%(.*?)%\]!', 'pick_one', $content); 
} 

function pick_one($matches) { 
    $choices = explode('|', $matches[1]); 
    return $choices[rand(0, count($choices)-1)]; 
} 

$my_source_page = file_get_contents('path/to/source';} 
$my_source1_spin = doSpin($my_source_page); 
$my_source1_replace = doReplace($my_source1_spin); 
$my_source1_final = addslashes($my_source1_replace); 

//Now do something with $my_source1_final 
+0

雖然這應該不會影響性能,您應該使用array_rand()在PICK_ONE()函數: 回報$選擇[array_rand( $選擇)]。 – Inspire 2010-03-07 15:41:06

回答

1

說實話,我沒有看到你發佈的代碼有什麼問題。代碼中的主要瓶頸很可能是file_get_contents調用。

我唯一能看到的是你將字符串分配給不同的變量(從$ my_source開始的四個變量),比使用1或2個變量會使用更多的內存。

但是,除非您在繁忙的網站上頻繁地將大量文本讀入內存,否則我認爲您不必擔心您發佈的代碼。你自己說的,你不必在目前任何性能問題;)