Monthly Archives: October 2011

qTranslate qtrans_use recursion optimization

This is another post (first post) about qTranslate performance optimization. This plugin really slows down the blog I’m administrating, so it keeps taunting me to optimize it’s execution. The already optimized (translation of options disabled) plugin adds about 150ms to rendering time. This enhancement saves about 60ms.

Webgrind analysis, before I made the changes, looks like this:
qTranslate + Webgring = before optimization

The changed “function qtrans_use” has some extra code added. The idea is, not to call recursions, when it’s not needed:

function qtrans_use($lang, $text, $show_available=false) {
    $split_regex = "#(|\[:[a-z]{2}\])#ism";
    if (is_string($text)) {
        if (!preg_match($split_regex, $text)) {
            return $text;
        }
    }

    global $q_config;
    // return full string if language is not enabled
    if(!qtrans_isEnabled($lang)) return $text;
    if(is_array($text)) {
        // handle arrays recursively
        foreach($text as $key => $t) {
            $transNeeded = true;
            if (is_string($t)) {
                if (!preg_match($split_regex, $t)) {
                    $transNeeded = false;
                }
            }
            if ($transNeeded) {
                $text[$key] = qtrans_use($lang,$t,$show_available);
            }
        }
        return $text;
    }

    if(is_object($text)||@get_class($text) == '__PHP_Incomplete_Class') {
        foreach(get_object_vars($text) as $key => $t) {
            $transNeeded = true;
            if (is_string($t)) {
                if (!preg_match($split_regex, $t)) {
                    $transNeeded = false;
                }
            }
            if ($transNeeded) {
                $text->$key = qtrans_use($lang,$t,$show_available);
            }
        }
        return $text;
    }
    ...

The Webgrind analysis looks much nicer now:
qTranslate + Webgring = after optimization