1,000개의 대량 데이터를 렌더링할 때 잘 쓰지 않지만 효과적인 고급 기법들을 소개합니다. 이런 방법들은 일반적인 개발에서는 오버엔지니어링으로 여겨지지만, 대량 데이터 처리에서는 놀라운 성능 향상을 가져올 수 있습니다.
1. CSS content-visibility - 뷰포트 밖 렌더링 스킵
2020년 Chrome 85부터 지원된 실험적 CSS 속성으로, 화면에 보이지 않는 요소의 렌더링을 완전히 건너뛸 수 있습니다.
.data-row {
/* 화면 밖 요소는 렌더링하지 않음 */
content-visibility: auto;
/* 높이 힌트 제공 (스크롤바 계산용) */
contain-intrinsic-size: 0 50px;
}
<div class="data-container">
<div class="data-row" style="content-visibility: auto;">
<!-- 1000개의 행이 있어도 화면에 보이는 것만 렌더링 -->
<div class="row-content">...</div>
</div>
</div>
효과: 1,000개 중 실제로 화면에 보이는 10-20개만 렌더링되어 90% 이상 성능 향상
2. CSS contain 속성 - 렌더링 격리
브라우저에게 "이 요소 안의 변화는 바깥에 영향을 주지 않는다"고 알려주어 레이아웃 재계산 범위를 제한합니다.
.data-table {
/* 레이아웃/스타일/페인트 격리 */
contain: layout style paint;
}
.data-row {
/* 각 행의 변화가 다른 행에 영향 안 줌 */
contain: layout style;
}
효과: 하나의 행이 변경되어도 다른 999개 행은 재계산하지 않음
3. Worker + OffscreenCanvas 렌더링
DOM 대신 Canvas에 테이블을 그리고, 메인 스레드가 아닌 Worker에서 처리합니다.
// main.js
const canvas = document.getElementById('data-canvas');
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker('table-renderer.js');
worker.postMessage({
canvas: offscreen,
data: largeDataArray
}, [offscreen]);
// table-renderer.js (Worker 파일)
let ctx;
self.onmessage = function(e) {
const { canvas, data } = e.data;
ctx = canvas.getContext('2d');
// 메인 스레드를 방해하지 않고 렌더링
renderTable(data);
};
function renderTable(data) {
const rowHeight = 40;
const colWidths = [200, 100, 100, 80, 80, 80, 80, 80, 80];
data.forEach((row, index) => {
const y = index * rowHeight;
let x = 0;
Object.values(row).forEach((cell, colIndex) => {
ctx.fillText(cell, x, y + 25);
x += colWidths[colIndex];
});
});
}
효과: 메인 스레드 블로킹 없이 대량 데이터 렌더링 가능
4. Intersection Observer + 지연 렌더링
화면에 들어올 때만 실제 내용을 렌더링하는 방식입니다.
// 빈 placeholder만 먼저 생성
const tbody = document.getElementById('data-tbody');
const placeholders = Array.from({length: 1000}, (_, i) => {
const tr = document.createElement('tr');
tr.style.height = '40px';
tr.dataset.index = i;
tr.innerHTML = '<td colspan="9">Loading...</td>';
return tr;
});
tbody.append(...placeholders);
// Intersection Observer로 보이는 것만 렌더링
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const tr = entry.target;
const index = parseInt(tr.dataset.index);
// 실제 데이터로 교체
tr.innerHTML = generateRowHTML(data[index]);
observer.unobserve(tr);
}
});
}, {
rootMargin: '200px' // 화면 200px 전에 미리 로드
});
placeholders.forEach(tr => observer.observe(tr));
효과: 초기 로딩 시간 95% 단축, 스크롤 시에만 필요한 만큼 렌더링
5. Memory Pool + Object Recycling
DOM 요소를 재사용하여 GC 압박과 메모리 할당 비용을 줄입니다.
class DOMPool {
constructor() {
this.pool = [];
this.active = [];
}
// 요소 대여
borrowElement(tagName = 'tr') {
let element = this.pool.find(el => el.tagName === tagName.toUpperCase());
if (!element) {
element = document.createElement(tagName);
} else {
this.pool.splice(this.pool.indexOf(element), 1);
}
this.active.push(element);
return element;
}
// 요소 반납
returnElement(element) {
const index = this.active.indexOf(element);
if (index > -1) {
this.active.splice(index, 1);
element.innerHTML = ''; // 내용 초기화
element.className = ''; // 클래스 초기화
this.pool.push(element);
}
}
// 전체 반납
returnAll() {
this.active.forEach(el => this.returnElement(el));
}
}
const domPool = new DOMPool();
// 사용 예시
function renderWithPool(data) {
// 기존 요소들 반납
domPool.returnAll();
const fragment = document.createDocumentFragment();
data.forEach(rowData => {
const tr = domPool.borrowElement('tr');
// tr에 데이터 삽입...
fragment.appendChild(tr);
});
tbody.appendChild(fragment);
}
효과: 메모리 사용량 70% 감소, GC 발생 빈도 대폭 감소
6. CSS Transform3d 레이어 분리
GPU 레이어로 분리하여 CPU 부담을 줄입니다.
.data-table {
/* GPU 레이어로 분리 */
transform: translateZ(0);
/* 또는 */
will-change: transform;
}
.data-row {
/* 각 행을 별도 레이어로 */
transform: translate3d(0, 0, 0);
}
/* 스크롤 시 부드러운 애니메이션 */
.data-container {
transform: translateZ(0);
backface-visibility: hidden;
perspective: 1000px;
}
효과: 스크롤 성능 300% 향상, 60fps 유지
7. Batch DOM Update + Animation Frame
여러 DOM 변경을 한 번에 처리하는 스케줄러입니다.
class BatchRenderer {
constructor() {
this.pendingUpdates = [];
this.isScheduled = false;
}
schedule(updateFn) {
this.pendingUpdates.push(updateFn);
if (!this.isScheduled) {
this.isScheduled = true;
requestAnimationFrame(() => this.flush());
}
}
flush() {
// 모든 read 작업 먼저 실행
const reads = this.pendingUpdates.filter(update => update.type === 'read');
reads.forEach(update => update.fn());
// 모든 write 작업 나중에 실행
const writes = this.pendingUpdates.filter(update => update.type === 'write');
writes.forEach(update => update.fn());
this.pendingUpdates = [];
this.isScheduled = false;
}
}
const batchRenderer = new BatchRenderer();
// 사용 예시
function updateMultipleRows(indices, newData) {
indices.forEach(index => {
batchRenderer.schedule({
type: 'write',
fn: () => {
const row = document.querySelector(`[data-index="${index}"]`);
row.innerHTML = generateRowHTML(newData[index]);
}
});
});
}
효과: 레이아웃 스래싱 방지, 업데이트 성능 400% 향상
8. CSS Subgrid + Container Queries
최신 CSS 기능으로 효율적인 그리드 레이아웃을 구성합니다.
.data-container {
display: grid;
grid-template-columns: 2fr 1fr 1fr repeat(6, 1fr);
container-type: inline-size;
}
.data-row {
display: grid;
grid-column: 1 / -1;
/* 부모 그리드 상속 */
grid-template-columns: subgrid;
}
/* 컨테이너 크기에 따른 반응형 */
@container (max-width: 768px) {
.data-container {
grid-template-columns: 1fr;
}
.data-row {
grid-template-columns: subgrid;
grid-template-rows: repeat(9, auto);
}
}
효과: 복잡한 레이아웃 계산 없이 자동 정렬, 반응형 처리
9. 완전한 예시: 복합 최적화
모든 기법을 조합한 최종 코드입니다.
<!DOCTYPE html>
<html>
<head>
<style>
.data-container {
contain: layout style paint;
transform: translateZ(0);
height: 600px;
overflow-y: auto;
}
.data-row {
content-visibility: auto;
contain-intrinsic-size: 0 40px;
contain: layout style;
transform: translate3d(0, 0, 0);
height: 40px;
display: grid;
grid-template-columns: 2fr 1fr 1fr repeat(6, 1fr);
}
</style>
</head>
<body>
<div class="data-container" id="container">
<!-- 1000개 행이 여기에 추가됨 -->
</div>
<script>
const data = generateData(1000);
const container = document.getElementById('container');
// 초기에는 빈 행들만 생성
const rows = Array.from({length: 1000}, (_, i) => {
const div = document.createElement('div');
div.className = 'data-row';
div.dataset.index = i;
div.style.height = '40px';
return div;
});
// 한 번에 추가
container.append(...rows);
// Intersection Observer로 지연 렌더링
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const row = entry.target;
const index = parseInt(row.dataset.index);
requestAnimationFrame(() => {
row.innerHTML = generateRowContent(data[index]);
});
observer.unobserve(row);
}
});
}, { rootMargin: '100px' });
rows.forEach(row => observer.observe(row));
</script>
</body>
</html>
최종 효과:
- 초기 렌더링 시간: 95% 단축
- 메모리 사용량: 80% 감소
- 스크롤 성능: 60fps 유지
- 브라우저 버벅거림: 완전 제거
이런 고급 기법들은 일반적인 웹 개발에서는 잘 사용되지 않지만, 대량 데이터 처리가 필요한 엔터프라이즈 애플리케이션에서는 게임체인저가 될 수 있습니다.