/** * PerformanceAnalyzer - Detect performance bottlenecks and anti-patterns * Identifies: Nested loops, sync I/O, N+1 queries, memory leaks, blocking operations */ class PerformanceAnalyzer { constructor() { this.version = '1.0.0'; } /** * Analyze performance patterns * @param {Array} files - All files with content * @returns {Object} Performance analysis */ analyze(files) { const nestedLoops = this.detectNestedLoops(files); const syncIO = this.detectSynchronousIO(files); const nPlusOne = this.detectNPlusOneQueries(files); const memoryLeaks = this.detectMemoryLeakPatterns(files); const blockingOps = this.detectBlockingOperations(files); const inefficientRegex = this.detectInefficientRegex(files); const hotspots = this.identifyHotspots(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps); return { nestedLoops, synchronousIO: syncIO, nPlusOneQueries: nPlusOne, memoryLeaks, blockingOperations: blockingOps, inefficientRegex, hotspots, summary: this.generateSummary(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps, inefficientRegex) }; } /** * Detect nested loops (O(n²) or worse complexity) */ detectNestedLoops(files) { const issues = []; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); const loopStack = []; lines.forEach((line, lineIndex) => { const trimmed = line.trim(); // Detect loop start if (/\b(?:for|while|forEach|map|filter|reduce)\s*\(/.test(trimmed)) { loopStack.push({ type: this.identifyLoopType(trimmed), line: lineIndex + 1, depth: loopStack.length + 1 }); } // Detect loop end (simplified - check closing braces) if (trimmed === '}' && loopStack.length > 0) { const loop = loopStack.pop(); // Report nested loops if (loop.depth >= 2) { const complexity = this.calculateLoopComplexity(loop.depth); issues.push({ type: 'NESTED_LOOP', file: file.filePath, line: loop.line, depth: loop.depth, complexity, severity: loop.depth >= 3 ? 'CRITICAL' : 'HIGH', message: `Nested loop with depth ${loop.depth} (${complexity} complexity)`, recommendation: 'Consider using hash maps, caching, or algorithmic optimization', performanceImpact: this.estimatePerformanceImpact(loop.depth) }); } } }); }); return issues; } /** * Identify loop type */ identifyLoopType(line) { if (/\bfor\s*\(/.test(line)) return 'for'; if (/\bwhile\s*\(/.test(line)) return 'while'; if (/\bforEach\s*\(/.test(line)) return 'forEach'; if (/\bmap\s*\(/.test(line)) return 'map'; if (/\bfilter\s*\(/.test(line)) return 'filter'; if (/\breduce\s*\(/.test(line)) return 'reduce'; return 'loop'; } /** * Calculate loop complexity notation */ calculateLoopComplexity(depth) { const notations = ['O(n)', 'O(n²)', 'O(n³)', 'O(n⁴)', 'O(n⁵)']; return notations[depth - 1] || `O(n^${depth})`; } /** * Estimate performance impact */ estimatePerformanceImpact(depth) { const impacts = { 1: 'LINEAR - Acceptable', 2: 'QUADRATIC - May slow with large datasets', 3: 'CUBIC - Critical performance issue', 4: 'POLYNOMIAL - Severe performance bottleneck' }; return impacts[depth] || 'EXPONENTIAL - Catastrophic performance'; } /** * Detect synchronous I/O in async context */ detectSynchronousIO(files) { const issues = []; const syncPatterns = [ { pattern: /fs\.readFileSync\(/g, api: 'fs.readFileSync', alternative: 'fs.promises.readFile' }, { pattern: /fs\.writeFileSync\(/g, api: 'fs.writeFileSync', alternative: 'fs.promises.writeFile' }, { pattern: /fs\.readdirSync\(/g, api: 'fs.readdirSync', alternative: 'fs.promises.readdir' }, { pattern: /fs\.statSync\(/g, api: 'fs.statSync', alternative: 'fs.promises.stat' }, { pattern: /child_process\.execSync\(/g, api: 'child_process.execSync', alternative: 'child_process.exec with promises' }, { pattern: /child_process\.spawnSync\(/g, api: 'child_process.spawnSync', alternative: 'child_process.spawn' }, { pattern: /crypto\.pbkdf2Sync\(/g, api: 'crypto.pbkdf2Sync', alternative: 'crypto.pbkdf2 (async)' } ]; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); const isAsync = file.content.includes('async ') || file.content.includes('await '); lines.forEach((line, lineIndex) => { syncPatterns.forEach(({ pattern, api, alternative }) => { if (pattern.test(line)) { issues.push({ type: 'SYNCHRONOUS_IO', file: file.filePath, line: lineIndex + 1, api, severity: isAsync ? 'CRITICAL' : 'HIGH', message: `Synchronous I/O operation ${api} ${isAsync ? 'in async function' : ''}`, recommendation: `Replace with ${alternative}`, performanceImpact: 'Blocks event loop, reduces throughput' }); } pattern.lastIndex = 0; }); }); }); return issues; } /** * Detect N+1 query patterns */ detectNPlusOneQueries(files) { const issues = []; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); // Pattern: Query in loop let inLoop = false; let loopStartLine = 0; lines.forEach((line, lineIndex) => { // Detect loop if (/\b(?:for|while|forEach|map)\s*\(/.test(line)) { inLoop = true; loopStartLine = lineIndex + 1; } // Detect query inside loop if (inLoop) { const queryPatterns = [ /\.find\(/, /\.findOne\(/, /\.findById\(/, /\.get\(/, /\.query\(/, /SELECT\s+.*FROM/i, /await\s+\w+\.(find|get|query)/ ]; if (queryPatterns.some(pattern => pattern.test(line))) { issues.push({ type: 'N_PLUS_ONE_QUERY', file: file.filePath, line: lineIndex + 1, loopLine: loopStartLine, severity: 'CRITICAL', message: 'Database query inside loop (N+1 problem)', recommendation: 'Use batch loading, joins, or eager loading (e.g., .populate(), .include())', performanceImpact: 'Exponential database queries, severe performance degradation' }); } } // Detect loop end if (line.trim() === '}' && inLoop) { inLoop = false; } }); }); return issues; } /** * Detect memory leak patterns */ detectMemoryLeakPatterns(files) { const issues = []; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); lines.forEach((line, lineIndex) => { // Event listeners without removal if (/\.addEventListener\(|\.on\(/.test(line)) { const hasRemoveListener = file.content.includes('removeEventListener') || file.content.includes('.off(') || file.content.includes('cleanup'); if (!hasRemoveListener) { issues.push({ type: 'MEMORY_LEAK_EVENT_LISTENER', file: file.filePath, line: lineIndex + 1, severity: 'HIGH', message: 'Event listener added without cleanup', recommendation: 'Add removeEventListener in cleanup/unmount', performanceImpact: 'Memory accumulation over time' }); } } // Timers without clearing if (/setInterval\(|setTimeout\(/.test(line)) { const hasClearTimer = file.content.includes('clearInterval') || file.content.includes('clearTimeout'); if (!hasClearTimer) { issues.push({ type: 'MEMORY_LEAK_TIMER', file: file.filePath, line: lineIndex + 1, severity: 'HIGH', message: 'Timer created without cleanup', recommendation: 'Clear timer in cleanup function', performanceImpact: 'Memory and CPU accumulation' }); } } // Closures holding large objects if (/function\s*\([^)]*\)\s*{[\s\S]*?const\s+\w+\s*=\s*\[/.test(line)) { issues.push({ type: 'MEMORY_LEAK_CLOSURE', file: file.filePath, line: lineIndex + 1, severity: 'MEDIUM', message: 'Closure may capture large data structures', recommendation: 'Review closure scope, release references when done', performanceImpact: 'Prevents garbage collection' }); } // Unclosed resources const resourcePatterns = [ { pattern: /new\s+FileReader\(/, cleanup: 'abort()' }, { pattern: /fs\.createReadStream\(/, cleanup: '.close()' }, { pattern: /new\s+WebSocket\(/, cleanup: '.close()' }, { pattern: /database\.connect\(/, cleanup: '.disconnect()' } ]; resourcePatterns.forEach(({ pattern, cleanup }) => { if (pattern.test(line) && !file.content.includes(cleanup)) { issues.push({ type: 'UNCLOSED_RESOURCE', file: file.filePath, line: lineIndex + 1, severity: 'HIGH', message: 'Resource opened without explicit cleanup', recommendation: `Ensure ${cleanup} is called`, performanceImpact: 'Resource exhaustion, file descriptor leaks' }); } }); }); }); return issues; } /** * Detect blocking operations */ detectBlockingOperations(files) { const issues = []; const blockingPatterns = [ { pattern: /while\s*\(\s*true\s*\)/g, name: 'Infinite loop', severity: 'CRITICAL' }, { pattern: /for\s*\(\s*;\s*;\s*\)/g, name: 'Infinite for loop', severity: 'CRITICAL' }, { pattern: /\.sort\(\s*\)/g, name: 'Array sort (O(n log n))', severity: 'MEDIUM' }, { pattern: /JSON\.parse\(/g, name: 'JSON.parse (synchronous)', severity: 'LOW' }, { pattern: /JSON\.stringify\(/g, name: 'JSON.stringify (synchronous)', severity: 'LOW' }, { pattern: /crypto\.pbkdf2Sync\(/g, name: 'Synchronous crypto operation', severity: 'HIGH' }, { pattern: /\.match\([^)]{50,}\)/g, name: 'Complex regex match', severity: 'MEDIUM' } ]; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); lines.forEach((line, lineIndex) => { blockingPatterns.forEach(({ pattern, name, severity }) => { if (pattern.test(line)) { issues.push({ type: 'BLOCKING_OPERATION', file: file.filePath, line: lineIndex + 1, operation: name, severity, message: `Blocking operation: ${name}`, recommendation: this.getBlockingRecommendation(name), performanceImpact: 'Blocks event loop, reduces responsiveness' }); } pattern.lastIndex = 0; }); }); }); return issues; } /** * Get recommendation for blocking operation */ getBlockingRecommendation(operation) { const recommendations = { 'Infinite loop': 'Add exit condition or use worker thread', 'Infinite for loop': 'Add proper loop termination', 'Array sort (O(n log n))': 'Consider pre-sorting or using indexed structure', 'JSON.parse (synchronous)': 'For large JSON, consider streaming parser', 'JSON.stringify (synchronous)': 'For large objects, consider streaming serializer', 'Synchronous crypto operation': 'Use async version', 'Complex regex match': 'Simplify regex or use multiple simpler patterns' }; return recommendations[operation] || 'Optimize or make async'; } /** * Detect inefficient regex patterns */ detectInefficientRegex(files) { const issues = []; files.forEach(file => { if (!file.content) return; const lines = file.content.split('\n'); lines.forEach((line, lineIndex) => { // Find regex patterns const regexMatches = line.match(/\/([^\/]+)\/[gimuy]*/g) || []; regexMatches.forEach(regexStr => { // Detect catastrophic backtracking patterns const catastrophicPatterns = [ { pattern: /\(\.\*\)\+|\(\.\+\)\+/, issue: 'Nested quantifiers' }, { pattern: /\([^)]*\*[^)]*\)\*/, issue: 'Nested star operators' }, { pattern: /\([^)]*\+[^)]*\)\+/, issue: 'Nested plus operators' }, { pattern: /\([^|]+\|[^|]+\)\+/, issue: 'Alternation with quantifier' } ]; catastrophicPatterns.forEach(({ pattern, issue }) => { if (pattern.test(regexStr)) { issues.push({ type: 'CATASTROPHIC_BACKTRACKING', file: file.filePath, line: lineIndex + 1, regex: regexStr, issue, severity: 'CRITICAL', message: `Regex with potential catastrophic backtracking: ${issue}`, recommendation: 'Simplify regex, use atomic groups, or non-backtracking patterns', performanceImpact: 'Exponential time complexity, can hang application' }); } }); // Detect overly complex regex if (regexStr.length > 100) { issues.push({ type: 'COMPLEX_REGEX', file: file.filePath, line: lineIndex + 1, regex: regexStr.substring(0, 50) + '...', severity: 'MEDIUM', message: 'Overly complex regex pattern', recommendation: 'Break into smaller patterns or use parser', performanceImpact: 'Slow pattern matching' }); } }); }); }); return issues; } /** * Identify performance hotspots */ identifyHotspots(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps) { const allIssues = [ ...nestedLoops, ...syncIO, ...nPlusOne, ...memoryLeaks, ...blockingOps ]; // Group by file const byFile = {}; allIssues.forEach(issue => { if (!byFile[issue.file]) { byFile[issue.file] = { file: issue.file, issues: [], criticalCount: 0, highCount: 0, score: 0 }; } byFile[issue.file].issues.push(issue); if (issue.severity === 'CRITICAL') { byFile[issue.file].criticalCount++; byFile[issue.file].score += 10; } else if (issue.severity === 'HIGH') { byFile[issue.file].highCount++; byFile[issue.file].score += 5; } else { byFile[issue.file].score += 1; } }); // Top 10 hotspots return Object.values(byFile) .sort((a, b) => b.score - a.score) .slice(0, 10) .map(hotspot => ({ ...hotspot, priority: hotspot.criticalCount > 0 ? 'CRITICAL' : hotspot.highCount > 2 ? 'HIGH' : 'MEDIUM', recommendation: this.generateHotspotRecommendation(hotspot) })); } /** * Generate hotspot recommendation */ generateHotspotRecommendation(hotspot) { const recommendations = []; if (hotspot.criticalCount > 0) { recommendations.push(`Address ${hotspot.criticalCount} critical performance issues immediately`); } const types = hotspot.issues.map(i => i.type); if (types.includes('NESTED_LOOP')) { recommendations.push('Optimize nested loops with better algorithms or caching'); } if (types.includes('N_PLUS_ONE_QUERY')) { recommendations.push('Implement batch loading or eager loading for database queries'); } if (types.includes('SYNCHRONOUS_IO')) { recommendations.push('Convert synchronous I/O to async operations'); } return recommendations.length > 0 ? recommendations : ['Review and optimize performance patterns']; } /** * Generate summary */ generateSummary(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps, inefficientRegex) { return { totalIssues: nestedLoops.length + syncIO.length + nPlusOne.length + memoryLeaks.length + blockingOps.length + inefficientRegex.length, nestedLoops: nestedLoops.length, synchronousIO: syncIO.length, nPlusOneQueries: nPlusOne.length, memoryLeaks: memoryLeaks.length, blockingOperations: blockingOps.length, inefficientRegex: inefficientRegex.length, criticalIssues: [ ...nestedLoops.filter(i => i.severity === 'CRITICAL'), ...syncIO.filter(i => i.severity === 'CRITICAL'), ...nPlusOne, ...inefficientRegex.filter(i => i.severity === 'CRITICAL') ].length }; } } module.exports = PerformanceAnalyzer;