[Templating] Cached the result of escape() in order to improve performance (+470ms)

This commit is contained in:
Bernhard Schussek 2012-07-16 18:29:06 +02:00
parent 151b79a6ce
commit 0d0a968800

View File

@ -38,6 +38,7 @@ class PhpEngine implements EngineInterface, \ArrayAccess
protected $charset; protected $charset;
protected $cache; protected $cache;
protected $escapers; protected $escapers;
protected $escaperCache;
protected $globals; protected $globals;
protected $parser; protected $parser;
@ -334,6 +335,16 @@ class PhpEngine implements EngineInterface, \ArrayAccess
*/ */
public function escape($value, $context = 'html') public function escape($value, $context = 'html')
{ {
// If we deal with a scalar value, we can cache the result to increase
// the performance when the same value is escaped multiple times (e.g. loops)
if (is_scalar($value)) {
if (!isset($this->escaperCache[$context][$value])) {
$this->escaperCache[$context][$value] = call_user_func($this->getEscaper($context), $value);
}
return $this->escaperCache[$context][$value];
}
return call_user_func($this->getEscaper($context), $value); return call_user_func($this->getEscaper($context), $value);
} }
@ -372,6 +383,7 @@ class PhpEngine implements EngineInterface, \ArrayAccess
public function setEscaper($context, $escaper) public function setEscaper($context, $escaper)
{ {
$this->escapers[$context] = $escaper; $this->escapers[$context] = $escaper;
$this->escaperCache[$context] = array();
} }
/** /**
@ -489,6 +501,8 @@ class PhpEngine implements EngineInterface, \ArrayAccess
return $value; return $value;
}, },
); );
$this->escaperCache = array();
} }
/** /**