Any way to reduce htmlspecialchars() CPU usage?
Asked Answered
K

1

6

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?

Killy answered 17/4, 2013 at 12:32 Comment(3)
if you escape so much data, maybe its better to store it already escaped?Secession
@Artjom Kurapov, most of the data is added by users. In order to let them edit it, I would have to unescape it and then escape it again, which would be a real pain. That's only one of the cases...Killy
If you're short on cpu but not on storage space, you can store it both escaped an unescaped. Escape once, when it's updated, and whenever the user wants to edit, use the original one. This is something I used with markdown and I was satisfied with the results.Folk
C
1

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;
    }
}
Conan answered 4/5, 2013 at 16:39 Comment(2)
Conditional statements? Loops?Killy
Make them with PHP-inline tagsConan

© 2022 - 2024 — McMap. All rights reserved.