Files
infinite-canvas/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md
T
HouYunFei fb79a15508 docs(vercel-react-best-practices): 添加 Vercel React 最佳实践规则文档
- 添加 sections 定义文件,包含性能优化各领域分类
- 添加规则模板文件,规范文档结构和标签定义
- 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等
- 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等
- 添加服务端性能优化规则,包括 API 路
2026-05-21 15:22:11 +08:00

1.7 KiB

title, impact, impactDescription, tags
title impact impactDescription tags
Early Length Check for Array Comparisons MEDIUM-HIGH avoids expensive operations when lengths differ javascript, arrays, performance, optimization, comparison

Early Length Check for Array Comparisons

When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.

In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).

Incorrect (always runs expensive comparison):

function hasChanges(current: string[], original: string[]) {
  // Always sorts and joins, even when lengths differ
  return current.sort().join() !== original.sort().join()
}

Two 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.

Correct (O(1) length check first):

function hasChanges(current: string[], original: string[]) {
  // Early return if lengths differ
  if (current.length !== original.length) {
    return true
  }
  // Only sort when lengths match
  const currentSorted = current.toSorted()
  const originalSorted = original.toSorted()
  for (let i = 0; i < currentSorted.length; i++) {
    if (currentSorted[i] !== originalSorted[i]) {
      return true
    }
  }
  return false
}

This new approach is more efficient because:

  • It avoids the overhead of sorting and joining the arrays when lengths differ
  • It avoids consuming memory for the joined strings (especially important for large arrays)
  • It avoids mutating the original arrays
  • It returns early when a difference is found