这个例程如何更好地优化?
问题描述:
下面的例程对输入的超文本流进行两次扫描。第一遍是用户定义的短语选项的自旋替换。第二遍是在下面的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
答
说实话,我没有看到你发布的代码有什么问题。代码中的主要瓶颈很可能是file_get_contents调用。
我唯一能看到的是你将字符串分配给不同的变量(从$ my_source开始的四个变量),比使用1或2个变量会使用更多的内存。
但是,除非您在繁忙的网站上频繁地将大量文本读入内存,否则我认为您不必担心您发布的代码。你自己说的,你不必在目前任何性能问题;)
虽然这应该不会影响性能,您应该使用array_rand()在PICK_ONE()函数: 回报$选择[array_rand( $选择)]。 – Inspire 2010-03-07 15:41:06