xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / js-length-check-first.md

1.7 KB
1---
2title: Early Length Check for Array Comparisons
3impact: MEDIUM-HIGH
4impactDescription: avoids expensive operations when lengths differ
5tags: javascript, arrays, performance, optimization, comparison
6---
7
8## Early Length Check for Array Comparisons
9
10When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
11
12In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
13
14**Incorrect (always runs expensive comparison):**
15
16```typescript
17function hasChanges(current: string[], original: string[]) {
18  // Always sorts and joins, even when lengths differ
19  return current.sort().join() !== original.sort().join()
20}
21```
22
23Two 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.
24
25**Correct (O(1) length check first):**
26
27```typescript
28function hasChanges(current: string[], original: string[]) {
29  // Early return if lengths differ
30  if (current.length !== original.length) {
31    return true
32  }
33  // Only sort when lengths match
34  const currentSorted = current.toSorted()
35  const originalSorted = original.toSorted()
36  for (let i = 0; i < currentSorted.length; i++) {
37    if (currentSorted[i] !== originalSorted[i]) {
38      return true
39    }
40  }
41  return false
42}
43```
44
45This new approach is more efficient because:
46- It avoids the overhead of sorting and joining the arrays when lengths differ
47- It avoids consuming memory for the joined strings (especially important for large arrays)
48- It avoids mutating the original arrays
49- It returns early when a difference is found