Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/js-length-check-first.md
1---2title: Early Length Check for Array Comparisons3impact: MEDIUM-HIGH4impactDescription: avoids expensive operations when lengths differ5tags: javascript, arrays, performance, optimization, comparison6---78## Early Length Check for Array Comparisons910When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.1112In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).1314**Incorrect (always runs expensive comparison):**1516```typescript17function hasChanges(current: string[], original: string[]) {18// Always sorts and joins, even when lengths differ19return current.sort().join() !== original.sort().join()20}21```2223Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.2425**Correct (O(1) length check first):**2627```typescript28function hasChanges(current: string[], original: string[]) {29// Early return if lengths differ30if (current.length !== original.length) {31return true32}33// Only sort when lengths match34const currentSorted = current.toSorted()35const originalSorted = original.toSorted()36for (let i = 0; i < currentSorted.length; i++) {37if (currentSorted[i] !== originalSorted[i]) {38return true39}40}41return false42}43```4445This new approach is more efficient because:46- It avoids the overhead of sorting and joining the arrays when lengths differ47- It avoids consuming memory for the joined strings (especially important for large arrays)48- It avoids mutating the original arrays49- It returns early when a difference is found50