Files
2nd/10_Wiki/Topics/Architecture/불변성(Immutability).md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

5.3 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-불변성-immutability 불변성 (Immutability) 10_Wiki/Topics verified self
Immutability
Immutable Data
Persistent Data Structures
불변 자료구조
none A 0.9 applied
functional-programming
concurrency
data-structures
design
2026-05-10 pending
language framework
multi Immer/Immutable.js

불변성 (Immutability)

매 한 줄

"매 생성 후 의 state 의 mutate 의 X — 매 update 의 new value 의 produce.". 매 shared mutable state 의 concurrency · reasoning · debugging hell 의 root cause — 매 immutable data 의 매 reasoning 의 local 의 keep · race 의 eliminate · 매 time-travel · undo 의 cheap. 2026 modern stack (Rust ownership, Clojure, Immer, structural sharing) 은 매 immutability 의 performance cost 의 near-zero.

매 핵심

매 levels

  • Reference immutable: 매 variable rebind X (const x = ...).
  • Shallow immutable: 매 object reference X 의 change, 매 nested mutable 가능.
  • Deep immutable: 매 entire tree mutable X (Object.freeze 매 recursive).
  • Persistent: 매 update 의 structural sharing 의 통한 efficient (HAMT, finger tree).

매 benefits

  • Concurrency: 매 lock-free read · 매 race 의 X.
  • Equality: 매 reference equality 의 enough — prev === next (React memo).
  • Time-travel: 매 undo/redo · 매 debugging snapshot.
  • Predictability: 매 function 의 input 의 mutate X — 매 reason 의 local.

매 응용

  1. 매 React/Redux state — 매 immutable update 의 re-render 의 cheap detect.
  2. 매 Event sourcing — 매 event log immutable.
  3. 매 functional core, imperative shell pattern.

💻 패턴

JavaScript — Object spread (shallow)

const user = { name: "Ada", age: 30 };
const older = { ...user, age: 31 };  // user 의 unchanged

Immer — mutable syntax, immutable result

import { produce } from "immer";

const next = produce(state, draft => {
  draft.users[0].name = "Ada";   // 매 draft 의 freely mutate
  draft.todos.push({ text: "x" });
});
// next 매 new immutable, state 매 unchanged

Rust — ownership + immutable by default

let v = vec![1, 2, 3];          // immutable
let mut w = v.clone();          // explicit mut
w.push(4);
// fn 매 borrow as &T 의 read-only access
fn sum(xs: &[i32]) -> i32 { xs.iter().sum() }

Clojure — persistent data structures

(def m {:a 1 :b 2})
(def m2 (assoc m :c 3))   ; 매 m unchanged, structural sharing
(= (get m :c) nil)         ; true

Python — frozen dataclass

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class User:
    id: int
    name: str

u1 = User(1, "Ada")
u2 = replace(u1, name="Grace")  # 매 new instance

Immutable.js (Map / List)

import { Map } from "immutable";
const m = Map({ a: 1, b: 2 });
const m2 = m.set("c", 3);  // structural sharing

Event sourcing — append-only

interface Event { type: string; payload: any; ts: number; }
class Aggregate {
  private events: readonly Event[] = [];
  apply(e: Event) { return new Aggregate([...this.events, e]); }
  state() { return this.events.reduce(reducer, initial); }
}

React — useState 의 immutable update

const [todos, setTodos] = useState<Todo[]>([]);
// add
setTodos(prev => [...prev, newTodo]);
// update by id
setTodos(prev => prev.map(t => t.id === id ? { ...t, done: true } : t));
// remove
setTodos(prev => prev.filter(t => t.id !== id));

매 결정 기준

상황 Approach
매 React/Redux state Immer or spread
매 hot path mutation (10M+/s) Mutable + 매 boundary 에서 freeze
매 deeply nested update Immer (productivity > raw perf)
매 multi-thread shared Persistent + lock-free read
매 audit/compliance Event sourcing — append-only log

기본값: 매 default immutable, 매 measured hotspot 의 mutable optimize.

🔗 Graph

🤖 LLM 활용

언제: 매 mutation bug 의 hunt — 매 trace where state 의 escape, 매 immutable refactor 의 propose. 언제 X: 매 raw numeric kernel · 매 GPU buffer — 매 in-place 의 unavoidable.

안티패턴

  • Shallow freeze: Object.freeze(x) 매 nested 의 still mutable — 매 deep freeze 의 필요.
  • Mutating in reducer: Redux state.x = 1 — 매 silent bug, 매 detect 의 hard.
  • Copy 의 매 op: 매 deep clone 매 every update — 매 structural sharing 의 use.
  • Frozen 의 mutate 의 try: strict mode 매 throw — 매 silent fail 의 X.
  • Immutable 의 cargo cult: 매 single-threaded local var 의 over-immutable — 매 noise.

🧪 검증 / 중복

  • Verified (Okasaki Purely Functional Data Structures; Immer docs; Rust Book ch4).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — levels, persistent structures, language patterns