Created
June 7, 2015 14:54
-
-
Save EloB/828a2de9f1f9b37b21e3 to your computer and use it in GitHub Desktop.
Why is this regexp slow?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Slow regexp</title> | |
</head> | |
<body> | |
<script> | |
function convertHtmlToText(html) { | |
el.innerHTML = html; | |
return el.textContent || el.innerText; | |
} | |
var el = document.createElement('div'), | |
a = convertHtmlToText('a'), | |
b = convertHtmlToText('b'), | |
space = convertHtmlToText(' '), | |
nonBreakingSpace = convertHtmlToText(' '), | |
slowRegExpTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, | |
spaces, | |
text; | |
alert('Open console'); | |
console.log(slowRegExpTrim); | |
setTimeout(function() { | |
for(var tests = 0; tests < 32; tests++) { | |
spaces = ''; | |
for(var i = tests; i; i--) spaces += space + nonBreakingSpace; | |
text = a + spaces + b; | |
console.log(tests, text); | |
console.time('Slow regexp'); | |
text.replace(slowRegExpTrim, ''); | |
console.timeEnd('Slow regexp'); | |
} | |
}, 5000); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment