5

callback 和 promise 性能差距疑问

 2 years ago
source link: https://www.v2ex.com/t/789987
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

callback

import * as fs from 'fs';
import * as path from 'path';
function list_dir(dir: string) {
    fs.readdir(dir, 'utf-8', (err, files) => {
        files.forEach(file => {
            file = path.join(dir, file)
            fs.stat(file, (err, stat) => {
                if (stat.isDirectory()) {
                    list_dir(file)
                }
                if (stat.isFile()) {
                    file
                    // console.log("%O", file);
                }
            })
        });
    })
}

list_dir('.')

promise

import * as util from 'util';
import * as fs from 'fs';
import * as path from 'path';
async function list_dir(dir: string) {
    const readdir = util.promisify(fs.readdir);
    const stat = util.promisify(fs.stat);
    const files = await readdir(dir, 'utf-8')
    files.forEach(async file => {
        file = path.join(dir, file)
        const state = await stat(file)
        if (state.isDirectory()) {
            await list_dir(file)
        }
        if (state.isFile()) {
            file
            // console.log("%O", file);
        }
    })

}

list_dir('.')

性能测试结果

node ➜ /workspaces/typescript $ time node promise.js && time node callback.js

real    0m1.140s
user    0m1.136s
sys     0m1.292s

real    0m0.377s
user    0m0.368s
sys     0m0.534s
node ➜ /workspaces/typescript $ time node promise.js && time node callback.js

real    0m1.062s
user    0m1.132s
sys     0m1.184s

real    0m0.538s
user    0m0.470s
sys     0m0.784s
node ➜ /workspaces/typescript $ time node promise.js && time node callback.js

real    0m1.194s
user    0m1.221s
sys     0m1.308s

real    0m0.436s
user    0m0.393s
sys     0m0.651s
node ➜ /workspaces/typescript $ time node promise.js && time node callback.js

real    0m1.024s
user    0m1.165s
sys     0m1.027s

real    0m0.416s
user    0m0.313s
sys     0m0.653s
node ➜ /workspaces/typescript $ nodejs --version
v16.3.0
node ➜ /workspaces/typescript $ tsc --version
Version 4.3.5

有性能差异可以理解,但是这个性能差异过大,请问各位是我的写法有问题,还是其它原因导致的呢?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK