有什么方法可以减少htmlspecialchars()的CPU使用率?

时间:2013-04-17 12:32:16

标签: php performance twig cpu-usage htmlspecialchars

我有一个php 5.4 / mysql网站,每天有500万次点击,在nginxphp-fpm的Linux服务器上运行。数据库位于单独的服务器上。

我注意到,在高峰时段,我的网络服务器负载最多为15,而四核处理器则为4。我用xdebugxhprof分析了我的php应用程序,看到 90%的CPU工作是由htmlspecialchars() 函数在{{1}完成的我用来显示数据的模板。每页有时会有100到1000个Twig个电话。我试图减少无法逃避,但仍然无法避免。

有什么方法可以通过htmlspecialchars()功能减少CPU使用量?也许在PHP中存在某种缓存?还是有另一种方式?

1 个答案:

答案 0 :(得分:1)

不要使用Twig。只需使用以下代码的php文件:

<?php
// Load a php-file and use it as a template
function template($tpl_file, $vars=array()) {
    $dir='/usr/local/app/view/'.$tpl_file.'.php';
    if(file_exists($dir)){
        // Make variables from the array easily accessible in the view
        extract($vars);
        // Start collecting output in a buffer
        ob_start();
        require($dir);
        // Get the contents of the buffer
        $applied_template = ob_get_contents();
        // Flush the buffer
        ob_end_clean();
        return $applied_template;
    }
}