Снижение Big-O в существующем коде по принципу одной трансформации за раз с проверкой и откатом. Для нового кода — lemmaly, для математических оптимизаций — mathguard.

Звёзды49 917
Авторsickn33

Установка

SKILL.md

complexity-cuts — Lower Big-O on Existing Code

lemmaly prevents bad complexity before code is written. complexity-cuts fixes it after the fact: code already exists, it works, but its time or space complexity is worse than necessary.

Violating the letter of these rules is violating the spirit of the skill. Adapting "just a little" is how a faster-but-wrong rewrite ships.

When to Use This Skill

Use complexity-cuts when refactoring existing code that has poor Big-O:

  • Nested loops, O(n²) or worse scans, repeated work, redundant allocations, blown memory.
  • Stated symptoms: "this is slow on large inputs", "times out", "OOM", "too much memory", "reduce complexity", "optimize this algorithm".
  • N+1 query patterns in ORMs (Prisma, Drizzle, SQLAlchemy, Django, ActiveRecord).
  • await inside for over independent items causing serial latency.

For preventing bad complexity before code is written, use lemmaly. For math-level optimizations (Bloom, HLL, FFT, JL projection), escalate to mathguard.

The Iron Law

NO TRANSFORMATION WITHOUT EXISTING TESTS GREEN BEFORE AND AFTER

If the code has no tests, you write a characterization test first (golden input → current output). Then transform. Then verify the test still passes. If you skip this, the optimization can silently break callers — and faster-but-wrong is worse than slow-and-right.

Non-negotiable rules

  1. State current and target Big-O before touching code. In one line:

    • Current: time = O(?), space = O(?)
    • Target: time = O(?), space = O(?)
    • Dominant input dimension (n = what, how large in practice)

    If you cannot state current Big-O, you do not yet understand the code. Read more.

  2. Identify the bottleneck, do not guess. Point to the exact line(s) responsible for the dominant term. Nested loop? Repeated linear scan? Recomputation? Allocation inside a hot loop? The fix lives there, not elsewhere.

  3. One transformation at a time, with a verify-revert-stop loop. The loop is:

    1. Apply exactly one transformation from the playbook.
    2. Run the existing test suite (or the characterization test you wrote per the Iron Law).
    3. If any test breaks: revert immediately. Do not patch the test. Do not patch around the failure. Revert.
    4. Count reverts on this piece of code. If 3 reverts in a row, STOP optimizing. The bottleneck is wrong, the transformation is wrong, or the code has invariants you have not modeled. Escalate to invariant-guard and write the missing contract — do not try a fourth transformation.
    5. Only after a transformation lands green: pick the next one.

    Stacked changes hide regressions. Patched tests hide regressions louder.

  4. Preserve semantics exactly. Lower complexity must not change outputs, ordering guarantees, stability, or error behavior. If the optimization requires a semantic change (e.g. unordered output), call it out explicitly and confirm it is acceptable.

  5. No invented numbers. Never write "10x faster" or "saves 200MB" without measuring. Write <measured: TBD> and move on, or actually measure with a representative input.

  6. Always report the measured speedup ratio after a transformation lands. Once the new code is green, run a representative benchmark (same input, same machine, warm cache) and report before → after plus the ratio as N× faster (or N× less memory). One line, attached to the diff:

    p50:  186 ms → 1.1 ms   (169× faster, n=20,000, 200 samples)
    

    If you cannot measure (e.g. the win is purely asymptotic on inputs you don't have), say so explicitly: asymptotic only, no measurement — O(n²) → O(n). Never silently skip this step.

The transformation playbook

The vast majority of real-world Big-O wins come from a small set of moves. Try them in this order:

Time-complexity reductions

SmellFixTypical win
for x in A: if x in B where B is list/arrayConvert B to Set/Map onceO(n·m) → O(n+m)
Nested loop computing pairs/joinsHash-join on the key; index by lookup fieldO(n·m) → O(n+m)
Repeated .find / .indexOf / .includes inside a loopPrecompute index Map<key, item> outside loopO(n^2) → O(n)
Repeated recomputation of same valueMemoize / cache by input keyO(n·f(n)) → O(n + f(n))
Sort inside a loopSort once outsideO(n^2 log n) → O(n log n)
Linear scan for min/max/median repeatedlyHeap / sorted structureO(n·k) → O(n log k)
Recursive recomputation (naive Fibonacci shape)Memoize, or convert to iterative DPexponential → O(n)
String concatenation in a loop (some langs)Use builder / join / array.push then joinO(n^2) → O(n)
Repeated regex compile in loopCompile once outsideconstant-factor, large
Counting / grouping via nested loopSingle pass with Counter / Map<k, count>O(n^2) → O(n)
Sliding-window written as nested loopTwo-pointer / windowed sumO(n^2) → O(n)
Repeated prefix sumsPrecompute prefix array, O(1) range queriesO(n·q) → O(n+q)
Pairwise distance / containment checks on intervalsSort + sweep lineO(n^2) → O(n log n)
Top-K via full sortHeap of size KO(n log n) → O(n log k)
Repeated set membership in loop bodySet once, reuseO(n·m) → O(n)
await inside a for over independent itemsPromise.all / batched concurrencywall-clock O(n·latency) → O(latency)
ORM query inside a loop (N+1)IN (...) / select_related / bulk fetchO(n) round-trips → O(1)

Space-complexity reductions

SmellFixTypical win
Materializing whole list/array just to iterateGenerator / iterator / streamO(n) → O(1)
Building intermediate arrays via chained .map().filter().map() on huge dataSingle-pass loop or lazy pipelinek·O(n) → O(n) (often O(1) extra)
Caching every intermediate result of a recursionRolling window (keep last k states)O(n) → O(k)
Storing parents/visited for graph traversal when only count neededBitset / counter onlyO(n) → O(1)
Copying input to mutateIn-place mutation when caller allowsO(n) → O(1)
Reading entire file before processingStream line-by-line / chunkedO(file) → O(chunk)
Deep-clone for safety in a loopClone once, or use structural sharing / immutablesO(n·m) → O(n+m)
Holding references that prevent GC (closures, listeners, caches)Bound the cache (LRU), remove listeners, scope closures tightlyunbounded → bounded
Loading full result set from DBCursor / pagination / streaming queryO(rows) → O(page)
JSON.parse(JSON.stringify(x)) for cloningstructuredClone or targeted copyO(n) work and allocation removed

When you cannot lower asymptotic Big-O

Sometimes O(n log n) really is the floor. Then move to constant-factor wins:

  • Replace pointer-chasing structures with contiguous arrays (cache locality).
  • Hoist invariants out of loops.
  • Avoid allocation in the hot loop (reuse buffers).
  • Prefer typed arrays / native containers over boxed objects for numeric work.
  • Batch syscalls / I/O.

State explicitly: "Asymptotic floor is O(n log n); applying constant-factor optimizations only."

Required workflow

For each piece of code you optimize:

  1. Measure or estimate current Big-O. Write it down.
  2. Identify the bottleneck line(s). Point at them.
  3. Pick one transformation from the playbook. Name it.
  4. Apply it. One change.
  5. Verify behavior. Tests pass, or outputs match on a representative input.
  6. State new Big-O. Time and space.
  7. Repeat if more wins exist and are worth the complexity cost.

Canonical example — workflow vs no-workflow

The same optimization with and without the verify-revert-stop loop.

Bottleneck. getOrdersWithUsers() runs 10s on 10k orders. Cause: users.find(u => u.id === o.userId) inside the map → O(n·m).

Without the workflow — changes semantics AND patches the test

// No workflow: change semantics + the optimization in one go
export function getOrdersWithUsers(orders, users) {
  const userById = Object.fromEntries(users.map(u => [u.id, u]));
  return orders
    .map(o => ({ ...o, user: userById[o.userId] }))
    .filter(o => o.user); // silently drops orders whose user was deleted
}

Faster, and changes the result set. Existing tests catch it — but the diff also "fixes" a flaky test by removing the assertion that checked the old behavior. Ships green. Breaks the billing report two weeks later.

With the workflow — one transformation, semantics preserved

// Workflow applied:
//   Bottleneck: orders.map → users.find  (line 14)
//   Current: time = O(n·m), space = O(1)
//   Target:  time = O(n+m), space = O(m)
//   Transformation: precompute index Map<userId, User> outside the loop
//   Semantic risk: None — orders with missing users still emit `user: undefined` exactly as before
//   Reverts so far: 0

export function getOrdersWithUsers(orders, users) {
  const userById = new Map(users.map(u => [u.id, u]));
  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));
}

One transformation. Existing tests stay untouched. Run them. If green, ship. If red, revert (don't patch). After 3 reverts, stop and load invariant-guard — the bottleneck is wrong, or the function has a contract no one wrote down.

Output discipline

When proposing or applying an optimization, your message must contain — in this order:

  1. Bottleneck — file:line and one-sentence reason.
  2. Current complexity — time = O(?), space = O(?).
  3. Transformation — name from the playbook (or describe it if novel).
  4. New complexity — time = O(?), space = O(?).
  5. Semantic risk — anything callers might notice (ordering, stability, error timing). "None" is a valid answer if true.
  6. Measured speedup — before → after with the ratio as N× faster (or asymptotic only if not measured). One line, honest numbers.
  7. The diff.

If any of 1–6 is missing, the optimization is not ready to apply.

Stop conditions — do not optimize further when

  • Asymptotic Big-O already matches a known lower bound for the problem.
  • The input is provably small and bounded (n < ~100 and not on a hot path).
  • The optimization would obscure correctness or harm readability without a measured win.
  • The bottleneck is I/O or external service latency, not CPU/memory — go fix that instead.

Premature optimization past these points adds risk without payoff.

Rationalizations to watch for

ExcuseReality
"I already solved this in my head — just paste the diff and add labels after."Retrofitted labels lie about the reasoning order. Write bottleneck → complexity → transformation → diff in that order, or you are writing fiction.
"Stating the current Big-O is busywork — everyone can see the nested loop."If everyone can see it, writing one line costs nothing. If only you can see it, you just saved the reviewer's time.
"Semantic risk is None, skip that step.""None" is a valid answer — but write it. The next reader does not know which guarantees you considered.
"I'll do all three transformations in one diff."Stacked transformations hide regressions. One transformation, verify, repeat.
"It's just a small refactor, the workflow is overkill."Then it takes 30 seconds. The cases where you skip the workflow are the ones where you miss the optimization next to the obvious one.
"I'll measure later."Later is <measured: TBD> forever. Either measure now or accept the asymptotic argument as the only claim.

Red flags — STOP

  • Optimizing without stating current Big-O.
  • "This should be faster" without identifying a specific bottleneck line.
  • Stacking multiple transformations before verifying any one of them.
  • Claiming a speedup without measuring or without an asymptotic argument.
  • Lowering complexity by silently changing output semantics.
  • Rewriting code that runs once at startup with n = 12.

Verification checklist

Before claiming an optimization is complete:

  • <!-- -->Existing tests (or a written characterization test) were green BEFORE the transformation.
  • <!-- -->Exactly one transformation was applied.
  • <!-- -->Tests are green AFTER the transformation.
  • <!-- -->No test was modified, weakened, or skipped to make it pass.
  • <!-- -->Current Big-O and target Big-O are stated in the diff or PR description.
  • <!-- -->Semantic risk is written down ("None" is valid if true).
  • <!-- -->Measured speedup ratio is reported as before → after · N× faster (or explicitly marked asymptotic only if no measurement was possible).
  • <!-- -->If a measured claim was made (e.g. "3x faster"), the measurement command is included.
  • <!-- -->Revert count on this code is < 3.

Cannot check every box? The optimization is not done. Either revert or finish the gap — do not ship a half-verified speedup.

Limitations

  • Requires existing tests or a written characterization test. Without one, you cannot detect silent semantic regressions; the Iron Law refuses to skip this.
  • Asymptotic wins only; constant-factor work is a separate mode (clearly labeled). The playbook will not improve cache locality or SIMD utilization on its own.
  • Single-process scope. Distributed-system bottlenecks (consensus latency, replication lag, queue backpressure) are out of scope.
  • 3-revert rule is firm. If three transformations failed, the skill explicitly forces escalation to invariant-guard; он не позволяет попробовать четвёртый.
  • Измерение — на ответственности автора. complexity-cuts требует сообщать соотношение, но не запускает бенчмарк за вас — вы должны подготовить репрезентативный вход.
  • Не поможет для кода, ограниченного I/O. Если доминирующий фактор — сетевая задержка или диск, этот подход не даст результата — вместо этого исправьте паттерн I/O.

Тезис в одной строке

Существующий код заслужил свою медлительность по одному компромиссу за раз. complexity-cuts устраняет их по одной трансформации за раз — и отказывается выпускать оптимизацию без зелёного теста.

Связанные навыки

  • lemmaly — шлюз предотвращения; используйте при написании нового кода вместо рефакторинга существующего.
  • invariant-guard — цель эскалации, когда 3+ трансформации провалили тесты — недостающий элемент — это контракт, а не оптимизация.
  • mathguard — эскалация, когда достигнут классический предел и может выиграть приближённая или математически тяжёлая структура.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: complexity-cuts](https://darkplay.ru/ai/skills/sickn33-agentic-awesome-skills-complexity-cuts)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Polyglot Test Plannergithub · Составляет структурированные планы реализации тестов на основе результатов исследования…
36 140 ★
cavemanalirezarezvani · Режим сверхсжатого общения. Сокращает расход токенов на 20–50% (до 75%), убирая воду и…
510 комп.
karpathy-coderalirezarezvani · Практика дисциплины кодинга по 4 принципам Karpathy: явные допущения, упрощение, точечные…
510 комп.
scroll-worldoso95 · Лендинг со скролл-анимацией: камера влетает в сцены и переходит между ними без склеек…
1 комп.
trailmarktrailofbits · Строит многоязычные графы исходного кода для анализа безопасности: графы вызовов, карту…
122 комп.
claude-castanthropics · Стримы Twitch, YouTube и Kick рядом с сессиями Claude Code: звук через mpv, живой чат в…
38 комп.
cost-estimateanthropics · Сканирует любую кодовую базу (GitHub URL или локальный путь) и оценивает стоимость её…
38 комп.
cronocode-react-boxanthropics · Экспертное руководство по @cronocode/react-box, предотвращающее типичные ошибки ИИ.
38 комп.
dependency-evaluatoranthropics · Оценка npm и Python пакетов перед добавлением: метаданные, безопасность, сложность и…
38 комп.
hyperflowanthropics · Восемь связанных команд превращают сессию Claude Code в инженерный процесс.
38 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8