如何用performance进行性能调试

85 阅读1分钟

通过performance我们可以准确看到页面加载的时候每一部分加载所耗费的时间

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>worker performance optimization</title>
    
</head>
<body>
    <script>
        function a() {
           b();
        }
        function b() {
            let total = 0;
            for(let i = 0; i< 10*10000*10000; i++) {
                total += i;
            }
            console.log('b:', total);
        }

        a();
    </script>
    <script>
        function c() {
            d();
        }
        function d() {
            let total = 0;
            for(let i = 0; i< 1*10000*10000; i++) {
                total += i;
            }
            console.log('c:', total);
        }
        c();
    </script>
</body>
</html>

因为js中的两个计算量都很大,所以有两个long task的提示,我们的目标就是去优化掉long task

image.png

image.png

可以看到第二个long task的耗时还是比较短的,因为第二个的计算量还是比前面的少10倍

react中使用了fiber可中断的断掉js执行进程把控制权交给浏览器去渲染,但是这里我们没办法也没必要去中断,这时候我们可以用web worker去开两个新的线程

// index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>worker performance optimization</title>
  </head>
  <body>
    <script>
      function runWorker(url, num) {
        return new Promise((resolve, reject) => {
          const worker = new Worker(url);
          worker.postMessage(num);
          worker.addEventListener("message", function (evt) {
            resolve(evt.data);
          });
          worker.onerror = reject;
        });
      }
    </script>
    <script>
      function b() {
        runWorker("./worker.js", 10 * 10000 * 10000).then((res) => {
          console.log("b:", res);
        });
      }
      b();
    </script>
    <script>
      function d() {
        runWorker("./worker.js", 1 * 10000 * 10000).then((res) => {
          console.log("d:", res);
        });
      }
      d();
    </script>
  </body>
</html>
// worker.js
window.addEventListener('message', function(evt) {
    let total = 0;
    let num = evt.data;
    for(let i = 0; i< num; i++) {
        total += i;
    }
    window.postMessage(total);
});

image.png

image.png

可以看到主线程的时间变短了,还多了两个worker的线程,而且worker线程也出现了long task的提示,因为我们把主要的计算逻辑都放在了worker上