"매 capacity 가 power-of-two 일 때 % N 의 & (N-1) replacement". 매 modulo 의 expensive (CPU cycle 10-30) 의 single-cycle AND 로 대체. Ring buffer, hash table bucket, fixed-size LRU, lock-free queue 의 hot path 의 universal trick. CPU branch predictor 와 cache line 의 friendly.
매 핵심
매 정확성 조건
N 이 power-of-two: 2^k.
index % N == index & (N - 1) (unsigned 또는 non-negative).
N - 1 이 모든 lower bit 의 1 의 mask.
매 대표 사용 처
Ring buffer / circular queue.
Open-addressing hash table bucket index.
Game loop frame index modulo history size.
Hardware register address calc.
Lock-free SPSC/MPMC queue (Disruptor pattern).
매 응용
LMAX Disruptor (Java) — sequence & ringMask.
Linux kernel ringbuffer.
Redis hash table — sizemask.
V8 hidden class transitions table.
💻 패턴
Basic ring buffer (C)
#define RB_CAP 1024 // must be power of two
typedefstruct{intdata[RB_CAP];uint32_thead,tail;// free-running counters
}RingBuf;staticinlinevoidrb_push(RingBuf*r,intv){r->data[r->head&(RB_CAP-1)]=v;r->head++;}staticinlineintrb_pop(RingBuf*r){intv=r->data[r->tail&(RB_CAP-1)];r->tail++;returnv;}
TypeScript fixed-size circular log
classCircularLog<T>{privatebuf:(T|undefined)[]privatemask: numberprivatehead=0constructor(capacityPow2: number){if((capacityPow2&(capacityPow2-1))!==0)thrownewError('capacity must be power of two')this.buf=newArray(capacityPow2)this.mask=capacityPow2-1}push(v: T){this.buf[this.head&this.mask]=vthis.head++}recent(n: number):T[]{constout: T[]=[]for(leti=0;i<n;i++){constv=this.buf[(this.head-1-i)&this.mask]if(v!==undefined)out.push(v)}returnout}}
// producer
voidproduce(RingBuf*r,intv){uint32_th=atomic_load(&r->head);while(h-atomic_load(&r->tail)>=RB_CAP)cpu_relax();// full
r->data[h&(RB_CAP-1)]=v;atomic_store(&r->head,h+1);}
Branch-free wrap (negative-safe)
// for signed wrap, use bit-and after cast
intidx=((int)(counter)&((int)CAP-1));// counter must be non-negative
매 결정 기준
상황
Approach
Hot path, capacity 가 control 가능
Power-of-2 + masking
Capacity 가 user-input arbitrary
% (or round up to pow2)
Capacity 가 dynamic resize
resize 시 mask recompute
Signed counter
unsigned cast 또는 modulo
Hardware-aligned (cache line)
pow2 + alignment 조합
기본값: 매 ring/hash table 는 power-of-two + bitmask. 매 capacity 의 dynamic 이면 round-up.
🔗 Graph
응용: Object Pooling (오브젝트 풀링)
Adjacent: SharedArrayBuffer로 스레드 간 메모리 공유 효율 높이기 · Pointer Compression
🤖 LLM 활용
언제: 매 high-throughput data structure, lock-free queue, HFT, game engine frame loop.
언제 X: capacity 의 control 안 되거나 readability priority 인 일반 application code.
❌ 안티패턴
Non-pow2 size 에 mask 적용: 매 silent index out-of-range, data corruption.
Signed negative index 의 masking: -1 & (N-1) 의 N-1 이 됨 → 매 unsigned cast 또는 ((i % N) + N) % N pattern.
Capacity 1 의 mask 0: 매 always index 0, degenerate.
Premature application: 매 측정 없이 micro-optimization. 매 hot path 만 의 적용.