阿里云主机折上折
  • 微信号
Current Site:Index > Using the Performance panel in Chrome DevTools

Using the Performance panel in Chrome DevTools

Author:Chuan Chen 阅读数:30750人阅读 分类: 性能优化

Introduction to Chrome DevTools Performance Panel

The Performance panel in Chrome DevTools is a powerful tool for analyzing runtime performance of web pages. It records data such as CPU usage, memory consumption, and network requests during page loading and operation, helping developers identify performance bottlenecks.

Basic Operations of the Performance Panel

Starting a Performance Recording

  1. Open Chrome DevTools (F12 or Ctrl+Shift+I)
  2. Switch to the "Performance" tab
  3. Click the "Record" button (circular icon) to start recording
  4. Perform the user actions you want to analyze
  5. Click the "Record" button again to stop recording
// Example: Marking time points in code
console.time('render');
renderComponent();
console.timeEnd('render');  // Displays execution time in the console

Main Interface Areas

  • Overview Panel: Shows timelines for FPS, CPU usage, and network requests
  • Flame Chart: Displays detailed call stacks of activities on the main thread
  • Statistics Panel: Provides aggregated data for various metrics

Key Performance Metrics Analysis

Frame Rate (FPS) Analysis

The ideal frame rate is 60 FPS, meaning each frame has a time budget of 16.67ms. When the frame rate drops below 30 FPS, users will noticeably experience lag.

// Example code that may cause low FPS
function heavyCalculation() {
  let result = 0;
  for(let i = 0; i < 1000000; i++) {
    result += Math.sqrt(i) * Math.random();
  }
  return result;
}

// Performing heavy calculations within animation frames can cause dropped frames
function animate() {
  heavyCalculation();
  requestAnimationFrame(animate);
}
animate();

CPU Usage

The CPU chart shows which types of tasks occupied the CPU during different time periods:

  • Yellow: JavaScript execution
  • Purple: Style calculation and layout
  • Green: Painting and compositing

In-Depth Flame Chart Analysis

Call Stack Analysis

The flame chart's x-axis represents time, and the y-axis represents call stack depth. Each bar represents a function call, with width indicating execution time.

// Example call stack
function a() {
  b();
  c();
}

function b() {
  // Time-consuming operation
  for(let i = 0; i < 100000; i++) {}
}

function c() {
  // Another time-consuming operation
  for(let i = 0; i < 50000; i++) {}
}

a();  // The flame chart will show the complete stack of a calling b and c

Long Task Identification

Tasks exceeding 50ms are considered "long tasks" and will block the main thread. They appear as wide yellow blocks in the flame chart.

Memory Analysis Techniques

Memory Leak Detection

  1. Use the "Memory" panel to record heap snapshots
  2. Compare changes in object counts between multiple snapshots
  3. Look for unexpected growth in object types
// Potential memory leak example
let elements = [];
function addElement() {
  const el = document.createElement('div');
  document.body.appendChild(el);
  elements.push(el);  // Elements are permanently retained in the array
}

// Each button click leaks a DOM element
document.getElementById('btn').addEventListener('click', addElement);

Network Request Optimization

Waterfall Chart Analysis

  • View request queuing, blocking, and download times
  • Identify serial request chains
  • Discover uncompressed large resources
// Bad practice of serial requests
async function loadData() {
  const user = await fetch('/user');  // Wait for the first request to complete
  const posts = await fetch('/posts');  // Then start the second request
  return { user, posts };
}

// Improved parallel requests
async function loadDataBetter() {
  const [user, posts] = await Promise.all([
    fetch('/user'),
    fetch('/posts')
  ]);
  return { user, posts };
}

Rendering Performance Optimization

Layout Thrashing Issues

Layout thrashing refers to repeatedly forcing synchronous layouts, leading to performance degradation.

// Layout thrashing example
function resizeAll() {
  const boxes = document.querySelectorAll('.box');
  for(let i = 0; i < boxes.length; i++) {
    boxes[i].style.width = boxes[0].offsetWidth + 10 + 'px';  // Read followed by immediate write, causing forced synchronous layout
  }
}

// Improved version
function resizeAllBetter() {
  const boxes = document.querySelectorAll('.box');
  const width = boxes[0].offsetWidth;  // Batch reads first
  
  for(let i = 0; i < boxes.length; i++) {
    boxes[i].style.width = width + 10 + 'px';  // Then batch writes
  }
}

Advanced Feature Usage

Performance Monitor

Real-time monitoring of CPU usage, JS heap size, DOM node count, and other metrics.

Layer Analysis

Use the "Layers" panel to view composite layer situations. Excessive layers increase memory consumption.

/* Example CSS properties that create new layers */
.animated {
  will-change: transform;  /* Hints to the browser to prepare for optimization */
  transform: translateZ(0);  /* Older method to force layer creation */
}

Practical Case Studies

Case: Infinite Scroll List Optimization

The original implementation may cause increasing slowdowns:

// Original implementation
window.addEventListener('scroll', () => {
  if (nearBottom()) {
    loadMoreItems();  // Checks on every scroll
  }
});

// Optimized version
let ticking = false;
window.addEventListener('scroll', () => {
  if (!ticking) {
    requestAnimationFrame(() => {
      if (nearBottom()) {
        loadMoreItems();
      }
      ticking = false;
    });
    ticking = true;
  }
});

In the Performance panel, you can see the optimized version significantly reduces event handling time.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.