Skip to content

Instantly share code, notes, and snippets.

@galvez
Created September 11, 2023 20:10
Show Gist options
  • Save galvez/fc48f40ced3ec427aa3c1e10e88efa2c to your computer and use it in GitHub Desktop.
Save galvez/fc48f40ced3ec427aa3c1e10e88efa2c to your computer and use it in GitHub Desktop.
Sync vs Async FS
sync 3.8610219955444336
async 49.62050497531891
import { readFileSync } from 'node:fs'
import { open } from 'node:fs/promises'
import { performance } from 'node:perf_hooks'
import { strictEqual } from 'node:assert'
const lines = {sync: [], async: []}
{
const start = performance.now()
const file = ['./The-Gambler-by-Fyodor-Dostoyevsky.txt', 'utf8']
lines.sync.push(...readFileSync(...file).split(/\r?\n/g))
if (!lines.sync.at(-1)) {
lines.sync.splice(lines.sync.length-1, 1)
}
console.log('sync', performance.now() - start)
}
{
const start = performance.now()
const handle = await open('./The-Gambler-by-Fyodor-Dostoyevsky.txt', 'r')
for await (const line of handle.readLines()) {
lines.async.push(line)
}
console.log('async', performance.now() - start)
}
strictEqual(lines.async.length, lines.sync.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment