Performance & Optimization in JavaScript
From the JavaScript Regular Expressions cheat sheet · Advanced Techniques · verified Jul 2026
Performance & Optimization
Writing efficient regular expressions
javascript
// Avoid catastrophic backtracking
// Bad: Nested quantifiers
/(x+x+)+y/.test("xxxxxxxxxxxxxxxxxxxx") // Very slow!
// Good: Remove the nested quantifier (JS has no atomic
// groups / possessive quantifiers to stop backtracking)
/x+y/.test("xxxxxxxxxxxxxxxxxxxx") // Fast
// Or emulate an atomic group: lookahead + backreference
/(?=(x+))\1y/.test("xxxxxxxxxxxxxxxxxxxx") // Fast
// Use non-capturing groups when not needed
/(?:https?):\/\// // Better than /(https?):\/\//
// Anchor patterns when possible
// Slower
/\d{3}-\d{4}/.test(longText)
// Faster
/^\d{3}-\d{4}$/.test(phoneNumber)
// Compile once, use many times
const regex = new RegExp(pattern) // Once
for (const item of items) {
regex.test(item) // Use compiled regex
}
// Be specific with character classes
// Slower
/.+@.+\..+/
// Faster
/[^\s@]+@[^\s@]+\.[^\s@]+/
// Avoid alternation when possible
// Slower
/cat|dog|bird/
// Faster (if applicable)
/(?:cat|dog|bird)/
// Even better (for word list)
new Set(['cat', 'dog', 'bird']).has(word)
// Use lazy quantifiers for better performance
// Can be slow with long strings
/<.*>/
// Often faster
/<.*?>/💡 Catastrophic backtracking can freeze your app
⚡ Compile regex once when using repeatedly
📌 Be as specific as possible with patterns
🟢 Sometimes a simple string method is faster than regex
performanceoptimization