From eb9f08cbb35e8dbbab4e8ccd3162ace58246fafc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=BE=D1=81=D1=82=D1=8F=20=D0=A2=D1=80=D0=B5=D1=82?= =?UTF-8?q?=D1=8F=D0=BA?= Date: Wed, 3 Jan 2018 11:25:44 +0200 Subject: [PATCH] Refactoring the old escape() function improved performance on 30-40% --- lib/marked.js | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/lib/marked.js b/lib/marked.js index f2fb9b6be7..c85f74ac95 100644 --- a/lib/marked.js +++ b/lib/marked.js @@ -1274,14 +1274,32 @@ Parser.prototype.tok = function() { */ function escape(html, encode) { - return html - .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); + if (encode) { + if (escape.escapeTest.test(html)) { + return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch] }); + } + } else { + if (escape.escapeTestNoEncode.test(html)) { + return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch] }); + } + } + + return html; } +escape.escapeTest = /[&<>"']/; +escape.escapeReplace = /[&<>"']/g; +escape.replacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; +escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; + function unescape(html) { // explicitly match decimal, hex, and named HTML entities return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) {