web-worker 獨立執行緒,效能最佳化

zjy4fun發表於2024-09-05

ref: https://github.com/zjy4fun/web-worker

分別使用主執行緒和 worker 執行緒處理一個耗時計算,看看對主執行緒上的 UI 渲染有什麼影響

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Worker</title>
</head>

<body>
    <script>
        function task() {
            let sum = 0;
            for (let i = 0; i < 1e9; i++) {
                sum += i;
            }
            return sum;
        }

        function mainThread() {
            console.time("主執行緒計算耗時");
            task();
            console.timeEnd("主執行緒計算耗時");
        }
        mainThread();
    </script>
    <h1>Main Thread</h1>
</body>

</html>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Worker</title>
</head>

<body>
    <script>
        function workerThread() {
            console.time("Web Worker計算耗時");
            const worker = new Worker("worker.js");
            worker.postMessage("Hello, Web Worker!");
            worker.onmessage = function (event) {
                console.timeEnd("Web Worker計算耗時");
                console.log("Received message from worker:", event.data);
            }
        }
        workerThread();
    </script>
    <h1>Web Worker Thread</h1>
</body>

</html>
self.onmessage = function (event) {
    function task() {
        let sum = 0;
        for (let i = 0; i < 1e9; i++) {
            sum += i;
        }
        return sum;
    }
    const result = task();
    self.postMessage(result);
};

對比效果

web-worker 獨立執行緒,效能最佳化

可以看出使用 web worker 可以避免讓主執行緒阻塞

相關文章