Skip to content

Commit

Permalink
30% faster
Browse files Browse the repository at this point in the history
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)
```
  • Loading branch information
joshgoebel authored Nov 23, 2020
1 parent b42947e commit cbff634
Showing 1 changed file with 10 additions and 26 deletions.
36 changes: 10 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* @private
*/

var matchHtmlRegExp = /["'&<>]/
var matchHtmlRegExp = /["'&<>]/g

/**
* Module exports.
Expand All @@ -30,21 +30,14 @@ module.exports = escapeHtml
* @public
*/

function escapeHtml (string) {
var str = '' + string
var match = matchHtmlRegExp.exec(str)

if (!match) {
return str
}

var escape
var html = ''
var index = 0
function escapeHtml (str) {
var lastIndex = 0
var html = ''
var escape = ''
var match

for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
while (match = matchHtmlRegExp.exec(str)) {
switch (str.charCodeAt(match.index)) {
case 34: // "
escape = '&quot;'
break
Expand All @@ -60,19 +53,10 @@ function escapeHtml (string) {
case 62: // >
escape = '&gt;'
break
default:
continue
}

if (lastIndex !== index) {
html += str.substring(lastIndex, index)
}

lastIndex = index + 1
html += str.substring(lastIndex, match.index)
lastIndex = match.index + 1
html += escape
}

return lastIndex !== index
? html + str.substring(lastIndex, index)
: html
return html + str.substring(lastIndex)
}

0 comments on commit cbff634

Please sign in to comment.