From b16b1f86b1d2a012655d529d7d2978a478ff3b23 Mon Sep 17 00:00:00 2001 From: sam marshall Date: Fri, 19 Aug 2016 14:32:51 +0100 Subject: [PATCH] MDL-55650 Library: s() function - tweak parameters for performance The s() function includes a comment saying that parameter options should be modified to improve performance once PHP 5.4 is required. Since Moodle has required PHP 5.4 for some time, we should probably make the change and remove the comment. According to my benchmarking, these changes make s() about 7% faster and will save a staggering 2ms from a typical course view that calls it 8,000 times. --- lib/tests/weblib_test.php | 26 ++++++++++++++++++++++++++ lib/weblib.php | 6 ++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/tests/weblib_test.php b/lib/tests/weblib_test.php index a8c10f62ad9..0d7faf686fc 100644 --- a/lib/tests/weblib_test.php +++ b/lib/tests/weblib_test.php @@ -86,6 +86,32 @@ class core_weblib_testcase extends advanced_testcase { $this->assertSame('An entity: б.', s('An entity: б.')); $this->assertSame('An entity: &amp;.', s('An entity: &.')); $this->assertSame('Not an entity: &amp;#x09ff;.', s('Not an entity: &#x09ff;.')); + + // Test all ASCII characters (0-127). + for ($i = 0; $i <= 127; $i++) { + $character = chr($i); + $result = s($character); + switch ($character) { + case '"' : + $this->assertSame('"', $result); + break; + case '&' : + $this->assertSame('&', $result); + break; + case "'" : + $this->assertSame(''', $result); + break; + case '<' : + $this->assertSame('<', $result); + break; + case '>' : + $this->assertSame('>', $result); + break; + default: + $this->assertSame($character, $result); + break; + } + } } public function test_format_text_email() { diff --git a/lib/weblib.php b/lib/weblib.php index 530a1f02119..eb6c4ea254f 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -96,10 +96,8 @@ function s($var) { return '0'; } - // When we move to PHP 5.4 as a minimum version, change ENT_QUOTES on the - // next line to ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, and remove the - // 'UTF-8' argument. Both bring a speed-increase. - return preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;', htmlspecialchars($var, ENT_QUOTES, 'UTF-8')); + return preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;', + htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)); } /**