将字符串连接大小写性能问题在PHP


Will string concat case performant issue in PHP?

我在PHP中看到一些这样的代码

public function fetch()
{
    $xml = '';
    $xml .= '<' . '?xml version="1.0" encoding="utf-8"?' . '>' . "'n";
    $xml .= '<rss version="2.0">';
    $xml .= '<channel>';
    $xml .= '<title>TEST</title>';
    $xml .= '<description>TEST</description>';
    foreach ($this->items as $item)
    {
        $xml .= '<item>';
        $xml .= '<title>' . $item['title'] . '</title>';
        $xml .= '<description>' . $item['body'] . '</description>';
        $xml .= '</item>';
    }
    $xml .= '</channel>';
    $xml .= '</rss>';
    return $xml;
}

代码使用了大量的字符串concat(.=),你认为这不是一个好方法吗?这看起来会给我避免不必要的内存使用。

这些代码是MCV的"VIEW"的一部分,函数已经在"items"数组中获得了处理过的数据。这个函数会进行渲染。

你会同意而不是

echo $this->fetch();

使用模板文件更好吗?像这样:

include('template.php');

,然后在template.php:

<?xml version="1.0" encoding="utf-8">
<rss version="2.0">
<channel>
<title>TEST</title>
<description>TEST</description>
    <?
    foreach ($this->items as $item){
        echo '<item>';
        echo '<title>' . $item['title'] . '</title>';
        echo '<description>' . $item['body'] . '</description>';
        echo '</item>';
    }
    ?>
</channel>
</rss>

我认为第二种方法会更好。你同意吗?还有其他评论吗?

编辑:

一个用户指出使用模板也有它的不足。那么,你什么时候会使用这个模板,什么时候不用呢?(那些教程总是告诉我,无论如何我都可以使用模板,我有点困惑。)

使用模板不一定更好,因为它是一个I/O操作(I/O操作通常是昂贵的)。相比之下,串联的性能要高出几倍。您可以删除不必要的连接(如'<')。"?或使用HEREDOC/NOWDOC (http://php.net/manual/fr/language.types.string.php)

在一天结束时,只要应用程序不是纯粹的性能驱动,这主要取决于开发人员的选择。

编辑:如注释中所述,使用XML阅读器/写入器类将证明更健壮,并增加可维护性。