Programing/javascript

자바스크립트 실무 유틸 함수 시리즈 13 - 프론트엔드 성능 측정을 위한 간단한 유틸

Dongkkase 2025. 5. 1. 09:21
반응형

이번 13편에서는 프론트엔드 성능을 빠르게 측정하고 진단하는 데 유용한 유틸 함수들을 정리합니다. 웹 페이지의 반응 속도, 실행 시간, 프레임 드랍 등을 분석하여 개선 포인트를 찾을 수 있습니다.


✅ 1. measureExecutionTime (함수 실행 시간 측정)

📌 코드 블록의 실행 시간(ms) 측정

function measureExecutionTime(fn) {
  const start = performance.now();
  fn();
  const end = performance.now();
  return end - start;
}

📌 활용 예시

  • 무거운 작업 병목 분석
  • 렌더링 로직 성능 점검

✅ 2. markPerformance (퍼포먼스 마킹)

📌 시작-끝 마커 기반 시간 측정

function markPerformance(label, task) {
  performance.mark(`${label}-start`);
  const result = task();
  performance.mark(`${label}-end`);
  performance.measure(label, `${label}-start`, `${label}-end`);
  return result;
}

📌 활용 예시

  • 특정 UI 인터랙션 처리 시간 측정
  • 외부 라이브러리 성능 테스트

✅ 3. fpsMonitor (프레임률 측정기)

📌 초당 프레임(Frame Per Second) 측정

function fpsMonitor(duration = 1000) {
  return new Promise(resolve => {
    let frame = 0;
    const start = performance.now();

    function count() {
      const now = performance.now();
      if (now - start < duration) {
        frame++;
        requestAnimationFrame(count);
      } else {
        resolve(Math.round(frame * (1000 / duration)));
      }
    }
    requestAnimationFrame(count);
  });
}

📌 활용 예시

  • 애니메이션 최적화 여부 점검
  • GPU 부하 테스트

✅ 4. logMemoryUsage (메모리 사용량 로그)

📌 브라우저에서 제공하는 메모리 정보 출력

function logMemoryUsage() {
  if (performance.memory) {
    const { usedJSHeapSize, totalJSHeapSize } = performance.memory;
    console.log(`Memory: ${(usedJSHeapSize / 1024 / 1024).toFixed(2)} MB / ${(totalJSHeapSize / 1024 / 1024).toFixed(2)} MB`);
  } else {
    console.warn('Memory API not supported.');
  }
}

📌 활용 예시

  • 리소스 누수 탐지
  • SPA에서 누적 메모리 확인

✅ 5. logNavigationTiming (네트워크 및 로딩 측정)

📌 페이지 로딩 시간 정보 분석

function logNavigationTiming() {
  const [entry] = performance.getEntriesByType('navigation');
  if (entry) {
    console.table({
      redirect: entry.redirectEnd - entry.redirectStart,
      dns: entry.domainLookupEnd - entry.domainLookupStart,
      connect: entry.connectEnd - entry.connectStart,
      ttfb: entry.responseStart - entry.requestStart,
      contentDownload: entry.responseEnd - entry.responseStart,
      domParsing: entry.domInteractive - entry.responseEnd,
      domContentLoaded: entry.domContentLoadedEventEnd - entry.domContentLoadedEventStart,
      total: entry.loadEventEnd - entry.startTime
    });
  }
}

📌 활용 예시

  • 페이지 로딩 병목 구간 파악
  • SEO 개선 및 퍼포먼스 진단

✅ 결론

프론트엔드 성능 측정은 사용자 경험 향상과 리소스 최적화에 중요한 역할을 합니다. 이번 시리즈에서 소개한 유틸 함수들은 코드 한 줄로 성능을 가볍게 측정하고 개선 아이디어를 얻는 데 도움을 줍니다.

반응형