スキル一覧に戻る
sehyun0518

early-length-check-for-array-comparisons

by sehyun0518

0🍴 0📅 2026年1月21日
GitHubで見るManusで実行

SKILL.md


name: Early Length Check for Array Comparisons impact: MEDIUM-HIGH description: avoids expensive operations when lengths differ tags: 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

スコア

総合スコア

50/100

リポジトリの品質指標に基づく評価

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

レビュー

💬

レビュー機能は近日公開予定です