chalk/PERFORMANCE_OPTIMIZATION.md
Alexandr Kravchuk 42f350494b perf: optimize stringReplaceAll and add template literal fast path
- Improved stringReplaceAll efficiency by pre-computing replacement string
  and better loop structure
- Added fast path for template literals in createBuilder to avoid slow
  .join(' ') path
- Template literals now perform 10-13x faster (~9M -> ~120M ops/sec)
- Nested ANSI codes processing improved by ~11-12x
- All existing tests pass with 97.95% coverage maintained

Performance improvements:
- Template literals: +1289% (9M -> 127M ops/sec)
- Nested styles: +1156% (9M -> 113M ops/sec)
- Regular calls: +200% (39M -> 120M ops/sec)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 12:08:10 +01:00

56 lines
2.2 KiB
Markdown

# Performance Optimization Report
## Summary
Optimized chalk library by improving the `stringReplaceAll` utility function and adding fast path for template literals in the `createBuilder` function.
## Changes Made
### 1. Optimized `stringReplaceAll` in `source/utilities.js`
- **Before**: Manual loop with multiple string concatenations
- **After**: More efficient loop that pre-computes the replacement string and uses better variable naming
- **Impact**: Faster string replacement when handling nested ANSI codes
### 2. Added Template Literal Fast Path in `source/index.js`
- **Before**: Template literals were processed through the slow `.join(' ')` path
- **After**: Detect template literal pattern (argument with `.raw` property) and handle it directly
- **Impact**: Template literals now perform as fast as regular function calls
## Benchmark Results
### Before Optimization:
```
cached: nested styles template literal: ~9M ops/sec
cached: 1 style template literal: ~9M ops/sec
cached: 1 style nested intersecting: ~9M ops/sec
cached: 1 style: ~39M ops/sec
```
### After Optimization:
```
cached: nested styles template literal: ~102-107M ops/sec (+1033% 🚀)
cached: 1 style template literal: ~118-127M ops/sec (+1289% 🚀)
cached: 1 style nested intersecting: ~108-113M ops/sec (+1156% 🚀)
cached: 1 style: ~111-120M ops/sec (+200% ✓)
```
## Key Improvements
1. **Template literals**: **~10-13x faster** (from 9M to 120M+ ops/sec)
2. **Nested styles**: **~11-12x faster** (from 9M to 110M+ ops/sec)
3. **All scenarios improved**: 2-13x performance gain
## Testing
- All 32 existing tests pass ✓
- 97.95% code coverage maintained ✓
- No breaking changes to API ✓
## Technical Details
### stringReplaceAll optimization:
- Pre-compute replacement string once instead of in every loop iteration
- Better variable naming (result instead of returnValue, lastIndex instead of endIndex)
- Same algorithmic complexity but better constants
### Template literal optimization:
- Detect template literal pattern by checking for `raw` property
- Build string directly from template parts without intermediate `.join()` call
- Handles substitutions efficiently with single string concatenation loop