Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

js-performance-patterns

БесплатноБез исполняемых скриптовНе проверен

Provides framework-agnostic JavaScript runtime performance patterns. Use when optimizing hot paths, loops, DOM operations, caching, or data structure choices…

PatternsDevот PatternsDev★ 261 звезда на GitHub

Об этом скилле

JavaScript Performance Patterns

Table of Contents

Runtime performance micro-patterns for JavaScript hot paths. These patterns matter most in tight loops, frequent callbacks (scroll, resize, animation frames), and data-heavy operations. They apply to any JavaScript environment — React, Vue, vanilla, Node.js.

When to Use

Reference these patterns when:

  • Profiling reveals a hot function or tight loop
  • Processing large datasets (1,000+ items)
  • Handling high-frequency events (scroll, mousemove, resize)
  • Optimizing build-time or server-side scripts
  • Reviewing code for performance in critical paths

Instructions

  • Apply these patterns only in measured hot paths — code that runs frequently or processes large datasets. Don't apply them to cold code paths where readability is more important than nanosecond gains.

Details

Overview

Micro-optimizations are not a substitute for algorithmic improvements. Address the algorithm first (O(n^2) to O(n), removing waterfalls, reducing DOM mutations). Once the algorithm is right, these patterns squeeze additional performance from hot paths.


1. Use Set and Map for Lookups

Impact: HIGH for large collections — O(1) vs O(n) per lookup.

Array methods like .includes(), .find(), and .indexOf() scan linearly. For repeated lookups against the same collection, convert to Set or Map first.

Avoid — O(n) per check:

const allowedIds = ['a', 'b', 'c', /* ...hundreds more */]

function isAllowed(id: string) {
  return allowedIds.includes(id) // scans entire array
}

items.filter(item => allowedIds.includes(item.id)) // O(n * m)

Prefer — O(1) per check:

const allowedIds = new Set(['a', 'b', 'c', /* ...hundreds more */])

function isAllowed(id: string) {
  return allowedIds.has(id)
}

items.filter(item => allowedIds.has(item.id)) // O(n)

For key-value lookups, use Map instead of scanning an array of objects:

// Avoid
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
const user = users.find(u => u.id === targetId) // O(n)

// Prefer
const userMap = new Map(users.map(u => [u.id, u]))
const user = userMap.get(targetId) // O(1)

2. Batch DOM Reads and Writes

Impact: HIGH — Prevents layout thrashing.

Interleaving DOM reads (e.g., offsetHeight, getBoundingClientRect) with DOM writes (e.g., style.height = ...) forces the browser to recalculate layout multiple times. Batch all reads first, then all writes.

Avoid — layout thrashing (read/write/read/write):

elements.forEach(el => {
  const height = el.offsetHeight    // read → forces layout
  el.style.height = `${height * 2}px` // write
})
// Each iteration forces a layout recalculation

Prefer — batched reads then writes:

// Read phase
const heights = elements.map(el => el.offsetHeight)

// Write phase
elements.forEach((el, i) => {
  el.style.height = `${heights[i] * 2}px`
})

For complex cases, use requestAnimationFrame to defer writes to the next frame, or use a library like fastdom.

CSS class approach — single reflow:

// Avoid multiple style mutations
el.style.width = '100px'
el.style.height = '200px'
el.style.margin = '10px'

// Prefer — one reflow
el.classList.add('expanded')
// or
el.style.cssText = 'width:100px;height:200px;margin:10px;'

3. Cache Property Access in Tight Loops

Impact: MEDIUM — Reduces repeated property resolution.

Accessing deeply nested properties or array .length in every iteration adds overhead in tight loops.

Avoid:

for (let i = 0; i < data.items.length; i++) {
  process(data.items[i].value.nested.prop)
}

Prefer:

const { items } = data
for (let i = 0, len = items.length; i < len; i++) {
  const val = items[i].value.nested.prop
  process(val)
}

This matters for arrays with 10,000+ items or when called at 60fps. For small arrays or infrequent calls, the readable version is fine.


4. Memoize Expensive Function Results

Impact: MEDIUM-HIGH — Avoids recomputing the same result.

When a pure function is called repeatedly with the same arguments, cache the result.

Simple single-value cache:

function memoize<T extends (...args: any[]) => any>(fn: T): T {
  let lastArgs: any[] | undefined
  let lastResult: any

  return ((...args: any[]) => {
    if (lastArgs && args.every((arg, i) => Object.is(arg, lastArgs![i]))) {
      return lastResult
    }
    lastArgs = args
    lastResult = fn(...args)
    return lastResult
  }) as T
}

const expensiveCalc = memoize((data: number[]) => {
  return data.reduce((sum, n) => sum + heavyTransform(n), 0)
})

Multi-key cache with Map:

const cache = new Map<string, Result>()

function getResult(key
Полный SKILL.md на GitHub

Установить js-performance-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл js-performance-patterns?

Provides framework-agnostic JavaScript runtime performance patterns. Use when optimizing hot paths, loops, DOM operations, caching, or data structure choices in performance-critical code.

Как установить скилл js-performance-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл js-performance-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить js-performance-patterns с