[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,95 +1,125 @@
|
||||
---
|
||||
id: wiki-2026-0508-ad-hoc-optimization
|
||||
title: Ad hoc Optimization
|
||||
title: Ad-hoc Optimization
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-ADOP-001]
|
||||
aliases: [Local Optimization, Point Optimization]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced, Optimization, ad-hoc, process-Efficiency, project-Management, software-design]
|
||||
verification_status: applied
|
||||
tags: [performance, optimization, anti-pattern]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: any
|
||||
framework: any
|
||||
---
|
||||
|
||||
# [[Ad-hoc-Optimization|Ad-hoc-Optimization]]
|
||||
# Ad-hoc Optimization
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "눈앞의 불만 끄기: 시스템 전체의 효율이나 장기적인 구조는 무시한 채, 지금 당장 문제가 되는 부분만 임시방편으로 빠르게 다듬어 '작동하는 것처럼' 보이게 만드는 조급한 최적화."
|
||||
## 매 한 줄
|
||||
> **"매 measure-then-fix-locally tactic"**. 매 system-wide 매 architectural improvement 의 opposite — 매 single profiler hot-spot 의 surgical fix. 매 effective when bounded, dangerous when systemic problem masked.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
Ad-hoc 최적화(임시적 최적화)는 전체적인 설계 원칙(Standardization)이나 전략적 방향성 없이, 특정 상황이나 예외적인 케이스에 대해서만 국소적으로 수행되는 최적화 작업을 의미합니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **위험 요인**:
|
||||
* **Technical Debt (기술적 부채)**: 당장은 빠르지만, 나중에 시스템 전체를 고칠 때 거대한 걸림돌이 됨.
|
||||
* **Shadow Complexity**: 보이지 않는 곳에 비정형적인 로직이 쌓여 시스템의 투명성이 낮아짐.
|
||||
* **Inconsistency**: 한 부분의 Ad-hoc 최적화가 다른 부분의 성능을 갉아먹는 '부작용' 발생 (Sub-optimization).
|
||||
2. **정당화되는 경우**:
|
||||
* **Hotfix**: 시스템이 완전히 붕괴될 위기에서 즉각적인 복구가 필요할 때.
|
||||
* **Rapid [[Prototyping|Prototyping]]**: 초기 아이디어를 검증하기 위해 거친 코드로 빠르게 구현해볼 때.
|
||||
3. **개선 프로세스**:
|
||||
* Ad-hoc 조치 후에는 반드시 '사후 병합(Refactoring)' 과정을 거쳐 해당 최적화를 표준 아키텍처 내로 편입시켜야 함.
|
||||
### 매 mechanism
|
||||
- 매 profiler → bottleneck → patch → re-profile loop.
|
||||
- 매 80/20 rule — 매 20% code 의 80% time 의 surgical strike.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거의 '결과 중심 개발 정책'은 Ad-hoc 최적화를 통해 일정을 맞추는 것을 권장했으나, 현대의 '지속 가능한 시스템 운영 정책'은 이를 잠재적 리스크로 규정하고 정기적인 코드 리뷰와 설계 승인(QC) 정책을 강화함(RL Update).
|
||||
- **정책 변화(RL Update)**: 인프라 운영 정책에서, 수동으로 Ad-hoc 설정을 변경하는 대신 모든 변화를 코드로 관리하는 'IaC (Infrastructure as Code) 정책'을 도입하여 임시방편적 개입을 원천 차단하는 방향으로 진화함.
|
||||
### 매 vs systematic
|
||||
- **Ad-hoc**: caching one query, inlining one loop.
|
||||
- **Systematic**: index strategy, algorithm change, architecture refactor.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Standardization vs Innovation|Standardization vs Innovation]], Workflow-InteGrity, [[Theory of Constraints (TOC)|Theory of Constraints (TOC)]], [[Software-Design-Principles|Software-Design-Principles]], [[Operations-Research|Operations-Research]]
|
||||
- **Modern Tech/Tools**: Refactoring tools, Static code [[Analysis|Analysis]], CI/CD automated [[Testing|Testing]].
|
||||
---
|
||||
### 매 응용
|
||||
1. Performance bug regressions (single function got slow).
|
||||
2. Hot path tuning post-profiling.
|
||||
3. Pre-launch polish.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Profile-first (Node.js)
|
||||
```ts
|
||||
import { performance } from 'perf_hooks';
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const t0 = performance.now();
|
||||
const result = expensiveFunction(input);
|
||||
console.log(`took ${performance.now() - t0}ms`);
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Memoize one hot function
|
||||
```ts
|
||||
const memo = new Map<string, Result>();
|
||||
function compute(key: string, input: Input): Result {
|
||||
if (memo.has(key)) return memo.get(key)!;
|
||||
const r = expensiveFunction(input);
|
||||
memo.set(key, r);
|
||||
return r;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Batch one N+1 query
|
||||
```ts
|
||||
// Before: O(N) DB roundtrips
|
||||
for (const u of users) u.posts = await db.posts.where({ userId: u.id });
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// After: 1 roundtrip
|
||||
const posts = await db.posts.whereIn('userId', users.map(u => u.id));
|
||||
const byUser = groupBy(posts, 'userId');
|
||||
users.forEach(u => u.posts = byUser[u.id] ?? []);
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Hot loop unroll (tight CPU path)
|
||||
```ts
|
||||
// Before
|
||||
for (let i = 0; i < n; i++) sum += arr[i];
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
// After (4x unrolled)
|
||||
let i = 0;
|
||||
for (; i + 3 < n; i += 4) {
|
||||
sum += arr[i] + arr[i+1] + arr[i+2] + arr[i+3];
|
||||
}
|
||||
for (; i < n; i++) sum += arr[i];
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Cache HTTP response (1-line fix)
|
||||
```ts
|
||||
app.get('/api/feed', cacheMiddleware({ ttl: 60 }), async (req, res) => {
|
||||
res.json(await buildFeed(req.user));
|
||||
});
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 1 hot function, rest 매 fine | Ad-hoc fix |
|
||||
| 매 systemic — many slow paths | Architectural refactor |
|
||||
| Pre-launch perf polish | Ad-hoc 매 first, systematic later |
|
||||
|
||||
**기본값**: Profile → ad-hoc fix → re-profile. 매 escalate to systematic only if 매 ad-hoc 매 insufficient.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Performance-Optimization]]
|
||||
- 변형: [[Caching]] · [[Memoization]]
|
||||
- Adjacent: [[Profiling]] · [[Premature-Optimization]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: measured bottleneck, bounded scope.
|
||||
**언제 X**: 매 system-wide perf issue (architectural fix needed); 매 unmeasured guess (premature optimization).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Optimizing without profiling**: 매 wrong target.
|
||||
- **Local fix masking systemic issue**: e.g., caching to hide N+1 query.
|
||||
- **Ad-hoc until 매 spaghetti**: 매 too many patches → architectural debt.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Knuth — premature optimization is the root of all evil; Brendan Gregg — Systems Performance).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Ad-hoc Optimization FULL with profile-first patterns |
|
||||
|
||||
Reference in New Issue
Block a user