Skip to content

Instantly share code, notes, and snippets.

@FauxFaux
Forked from Kirill89/readFileSync_vs_readFile.js
Last active March 19, 2022 04:12
Show Gist options
  • Save FauxFaux/079dc1c696cd60c8120a5ed9b18942c3 to your computer and use it in GitHub Desktop.
Save FauxFaux/079dc1c696cd60c8120a5ed9b18942c3 to your computer and use it in GitHub Desktop.
readFileSync vs readFile benchmark
const fs = require('fs');
const fsp = fs.promises;
const util = require('util');
const readFile = util.promisify(fs.readFile);
fs.writeFileSync('a', 'a');
const attempts = 10000;
function runInCallback(left, cb) {
fs.readFile('a', () => {
if (left > 0) {
runInCallback(left - 1, cb);
} else {
cb();
}
});
}
(async () => {
console.time('sync');
for (let i = 0; i < attempts; i++) {
fs.readFileSync('a');
}
console.timeEnd('sync');
console.time('async');
for (let i = 0; i < attempts; i++) {
await readFile('a');
}
console.timeEnd('async');
console.time('async experimental');
for (let i = 0; i < attempts; i++) {
const fh = await fsp.open('a', 'r');
await fh.close();
}
console.timeEnd('async experimental');
console.time('callback');
await new Promise(r => runInCallback(attempts, r));
console.timeEnd('callback');
console.time('nextTick');
for (let i = 0; i < attempts; i++) {
await new Promise(r => setImmediate(r));
}
console.timeEnd('nextTick');
})().catch(e => console.log(e));

Kirill's mac

sync: 350.449ms
async: 914.830ms
callback: 853.446ms
nextTick: 54.225ms

gcp outside kubes (node is too old for fs.promises)

sync: 151.101ms
async: 1480.068ms
callback: 1268.984ms
nextTick: 103.432ms

Faux's desktop

sync: 56.665ms
async: 265.667ms
async experimental: 152.745ms
callback: 234.420ms
nextTick: 27.763ms

pod on dev

sync: 157.621ms
async: 4021.526ms
async experimental: 2219.324ms
callback: 3815.933ms
nextTick: 70.360ms

pod on dev, UV_THREADPOOL_SIZE=1

sync: 175.504ms
async: 1856.070ms
async experimental: 1047.297ms
callback: 1793.691ms
nextTick: 78.269ms

pod on dev, UV_THREADPOOL_SIZE=1, taskset -c 1

sync: 145.509ms
async: 849.236ms
async experimental: 593.194ms
callback: 648.267ms
nextTick: 95.132ms

fau.xxx (2011 xeon, rotary discs)

sync: 85.945ms
async: 467.870ms
async experimental: 265.956ms
callback: 444.904ms
nextTick: 34.292ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment