From 0d0a9688003eb023654f5ec8246ac27be7bae382 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Mon, 16 Jul 2012 18:29:06 +0200 Subject: [PATCH] [Templating] Cached the result of escape() in order to improve performance (+470ms) --- src/Symfony/Component/Templating/PhpEngine.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/Symfony/Component/Templating/PhpEngine.php b/src/Symfony/Component/Templating/PhpEngine.php index 91be50d082..6f1c62ef05 100644 --- a/src/Symfony/Component/Templating/PhpEngine.php +++ b/src/Symfony/Component/Templating/PhpEngine.php @@ -38,6 +38,7 @@ class PhpEngine implements EngineInterface, \ArrayAccess protected $charset; protected $cache; protected $escapers; + protected $escaperCache; protected $globals; protected $parser; @@ -334,6 +335,16 @@ class PhpEngine implements EngineInterface, \ArrayAccess */ 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); } @@ -372,6 +383,7 @@ class PhpEngine implements EngineInterface, \ArrayAccess public function setEscaper($context, $escaper) { $this->escapers[$context] = $escaper; + $this->escaperCache[$context] = array(); } /** @@ -489,6 +501,8 @@ class PhpEngine implements EngineInterface, \ArrayAccess return $value; }, ); + + $this->escaperCache = array(); } /**