Skip to content

Commit cbff634

Browse files
authored
30% faster
If regex is so fast that it's worth using at the beginning of the function, why not use it for the stepping? ``` regex stepping x 280 ops/sec ±0.41% (83 runs sampled) original x 214 ops/sec ±0.60% (85 runs sampled) ```
1 parent b42947e commit cbff634

File tree

1 file changed

+10
-26
lines changed

1 file changed

+10
-26
lines changed

index.js

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* @private
1414
*/
1515

16-
var matchHtmlRegExp = /["'&<>]/
16+
var matchHtmlRegExp = /["'&<>]/g
1717

1818
/**
1919
* Module exports.
@@ -30,21 +30,14 @@ module.exports = escapeHtml
3030
* @public
3131
*/
3232

33-
function escapeHtml (string) {
34-
var str = '' + string
35-
var match = matchHtmlRegExp.exec(str)
36-
37-
if (!match) {
38-
return str
39-
}
40-
41-
var escape
42-
var html = ''
43-
var index = 0
33+
function escapeHtml (str) {
4434
var lastIndex = 0
35+
var html = ''
36+
var escape = ''
37+
var match
4538

46-
for (index = match.index; index < str.length; index++) {
47-
switch (str.charCodeAt(index)) {
39+
while (match = matchHtmlRegExp.exec(str)) {
40+
switch (str.charCodeAt(match.index)) {
4841
case 34: // "
4942
escape = '&quot;'
5043
break
@@ -60,19 +53,10 @@ function escapeHtml (string) {
6053
case 62: // >
6154
escape = '&gt;'
6255
break
63-
default:
64-
continue
6556
}
66-
67-
if (lastIndex !== index) {
68-
html += str.substring(lastIndex, index)
69-
}
70-
71-
lastIndex = index + 1
57+
html += str.substring(lastIndex, match.index)
58+
lastIndex = match.index + 1
7259
html += escape
7360
}
74-
75-
return lastIndex !== index
76-
? html + str.substring(lastIndex, index)
77-
: html
61+
return html + str.substring(lastIndex)
7862
}

0 commit comments

Comments
 (0)