Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to reduce htmlspecialchars() CPU usage?

I have a php 5.4/mysql website with 5 million hits per day, running on a linux server with nginx and php-fpm. Database is located on a separate server.

I've noticed, that at peak times, my webserver load gets up to 15, instead of normal 4 for quad core processor. I've profiled my php application with xdebug and xhprof, and saw, that 90% of CPU work is done by htmlspecialchars() function in Twig templates that I use to display data. There are sometimes from 100 to 1000 htmlspecialchars() calls per page. I've tried to reduce unnacessary escaping, but still it cannot be avoided.

Is there any way I can reduce CPU usage by htmlspecialchars() function? Maybe there is some kind of caching in php for this? Or there is there another way?

like image 893
Silver Light Avatar asked Apr 17 '13 12:04

Silver Light


Video Answer


1 Answers

Don't use Twig. Just use php-files with this code:

<?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;
    }
}
like image 93
Gustav Avatar answered Oct 13 '22 05:10

Gustav