I/O performance in Node.js worker threads

时光毁灭记忆、已成空白 提交于 2021-02-19 07:17:57

问题


Here's an example with worker thread that takes ~600ms on local machine for synchronous I/O:

const fs = require('fs');
const { isMainThread, Worker, parentPort, workerData } = require('worker_threads');

const filename = './foo.txt';

if (isMainThread) {
    (async () => {
        console.time('!');

        await new Promise((resolve, reject) => {
            const worker = new Worker(__filename, { workerData: filename });

            worker.on('message', resolve);
            worker.on('error', reject);
            worker.on('exit', (code) => {
                if (code !== 0)
                    reject(new Error(`Worker stopped with exit code ${code}`));
            });
        });

        console.timeEnd('!');   
    })().catch(console.error);
} else {
    for (let i = 0; i < 100; i++)
        fs.readFileSync(workerData);

    parentPort.postMessage('ok');
}

The same example with single thread takes ~2s for asynchronous I/O:

const fs = require('fs');

const filename = './foo.txt';

console.time('worker');

(function read(i) {
    if (i < 100) {
        fs.readFile(filename, () => read(++i));
        return;
    }

    console.timeEnd('worker');  
})(0);

Obviously, synchronous blocking operation is more efficient here.

Node.js worker thread reference states:

Workers are useful for performing CPU-intensive JavaScript operations; do not use them for I/O, since Node.js’s built-in mechanisms for performing operations asynchronously already treat it more efficiently than Worker threads can.

What are the grounds for this statement?

What is the difference between main and worker threads regarding I/O?

Isn't the purpose of a worker to not be limited to non-blocking asynchronous operations?

What are the circumstances under which I/O performance may be less efficient in worker threads?

来源:https://stackoverflow.com/questions/52648229/i-o-performance-in-node-js-worker-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!