简体   繁体   English

JS Worker 性能 - 解析 JSON

[英]JS Worker Performance - Parsing JSON

I'm experimenting with Workers as my user interface is very slow due to big tasks running in the background.我正在尝试使用 Workers,因为我的用户界面非常慢,因为在后台运行大量任务。

I'm starting at the simplest tasks such as parsing JSON.我从最简单的任务开始,例如解析 JSON。 See below for my very simple code to create an async function running on a Worke.请参阅下面的非常简单的代码来创建在 Worke 上运行的异步 function。

Performance wise there is a big difference between:性能方面有很大的区别:

JSON.parse(jsonStr);

and

await parseJsonAsync(jsonStr);

JSON.parse() takes 1ms whereas parseJsonAsync takes 102ms! JSON.parse() 需要 1 毫秒,而 parseJsonAsync 需要 102 毫秒!

So my question is: are the overheads really that big for running worker threads or am I missing something?所以我的问题是:运行工作线程的开销真的那么大还是我错过了什么?

const worker = new Worker(new URL('../workers/parseJson.js', import.meta.url));

export async function parseJsonAsync(jsonStr) {

    return new Promise(
        (resolve, reject) => {

            worker.onmessage = ({
                data: {
                    jsonObject
                }
            }) => {
                resolve(jsonObject);
            };

            worker.postMessage({
                jsonStr: jsonStr,
            });
        }
    );
}

parseJson.js parseJson.js

self.onmessage = ({
    data: {
        jsonStr
    }
}) => {

    let jsonObject = null;

    try {
        jsonObject = JSON.parse(jsonStr);
    } catch (ex) {

    } finally {
        self.postMessage({
            jsonObject: jsonObject
        });
    }
};

I share my benchmark code below.我在下面分享我的基准代码。 You can play around yourself.你可以自己玩。

You can tune the number of item in jsonStr by changing Array.from({ length: number }) .您可以通过更改Array.from({ length: number })来调整jsonStr中的项目数。 Or you can compare runTest(1000) vs runTest() to see time diff btw waiting for worker to start or not.或者您可以比较runTest(1000)runTest()以查看等待工作人员启动与否的时间差异。

My test shows it takes around 30ms to start the worker.我的测试显示启动工作器大约需要 30 毫秒。 Now if I wait a second for the worker to start, then I run the test, I got these numbers (unit in milliseconds):现在,如果我等待工作人员启动,然后运行测试,我得到了这些数字(以毫秒为单位):

#items #项目 main主要的 worker工人
1,000 1,000 0.2 0.2 2.1 2.1
10,000 10,000 1.3 1.3 9.8 9.8
100,000 100,000 15.4 15.4 73.5 73.5
1,000,000 1,000,000 165 165 854 854
10,000,000 10,000,000 2633 2633 15312 15312

 const blobURL = URL.createObjectURL( new Blob( [ "(", function () { self.onmessage = ({ data: { jsonStr } }) => { let jsonObject = null; try { jsonObject = JSON.parse(jsonStr); } catch (ex) { } finally { self.postMessage({ jsonObject: jsonObject, }); } }; }.toString(), ")()", ], { type: "application/javascript" } ) ); const worker = new Worker(blobURL); const jsonStr = "[" + Array.from({ length: 1000 }, () => `{"foo":"bar"}`).join(",") + "]"; async function parseJsonAsync(jsonStr) { return new Promise((resolve) => { worker.onmessage = ({ data: { jsonObject } }) => { resolve(jsonObject); // tiem end here const delta = performance.now() - t0; console.log("main-worker", delta); parseJsonInMain(jsonStr); }; const t0 = performance.now(); worker.postMessage({ jsonStr: jsonStr, }); }); } const test = () => parseJsonAsync(jsonStr); function runTest(delay) { if (delay) { setTimeout(test, delay); } else { test(); } } function parseJsonInMain(jsonStr) { let obj; try { const t0 = performance.now(); obj = JSON.parse(jsonStr); const delta = performance.now() - t0; console.log("main", delta); } catch {} } runTest(1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM