Qadam Roadmap
проектdocs/Agents/rules/performance-avoid-quadratic.md

performance-avoid-quadratic.md

Обновлён 1 апр. 2026 г., 12:41 · 0 комментариев


title: Avoid O(n^2) Algorithms — Design for Scale impact: CRITICAL impactDescription: Prevents performance collapse at scale tags: performance, algorithms, complexity

Паспорт документа

  • Статус документа: living standard
  • Актуально на: 28 марта 2026 года
  • Владелец: backend/platform-команда
  • Пересмотр: при изменении инженерной практики, CI/CD, архитектурных правил или локального workflow
  • Область применения: внутренние rule/reference-card документы для инженерной команды
  • Связанные документы:

Avoid O(n^2) Algorithms — Design for Scale

Impact: CRITICAL

The platform will grow. What works with 100 items can collapse with 10,000. Performance is something we build correctly from the start.

When building features, always ask: "How does this behave with 10,000 items? 100,000 leads?"

Common O(n^2) patterns to avoid:

  • Nested array iterations (.map inside .map)
  • .find, .filter, .some inside loops
  • Checking every item against every other item
  • Chained filters over large lists

Incorrect (O(n^2)):

// Bad: O(n^2) — checks every item against every subject
const filtered = items.filter(item => {
  return selectedSubjects.some(sub => sub.id === item.subjectId);
});
// For 1000 items and 50 subjects: 50,000 checks

Correct (O(n) with Set):

// Good: O(n) — Set lookup is O(1)
const subjectSet = new Set(selectedSubjects.map(s => s.id));
const filtered = items.filter(item => subjectSet.has(item.subjectId));
// For 1000 items and 50 subjects: ~1,050 operations

Better data structures:

  • Set/Map: O(1) lookups instead of .find or .includes on arrays
  • Sorting + binary search: For range queries on large datasets
  • Database-level filtering: Let PostgreSQL do the work — don't fetch all and filter in JS
  • Pagination: Never load entire tables — always paginate

Database-level is always better:

// Bad: fetch all, filter in JS
const allItems = await this.itemRepo.findAll();
const filtered = allItems.filter(i => i.subjectId === subjectId);

// Good: filter at database level
const filtered = await this.itemRepo.findBySubject(subjectId, { page, limit });