-
-
Save bluwy/3660a23295c11c8f6d972b20006509f1 to your computer and use it in GitHub Desktop.
fs access perf test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs' | |
let timer = process.hrtime() | |
for (let i = 0; i < 1000; i++) { | |
for (let j = 0; j < 1000; j++) { | |
let path = './non/' + i + '/' + j + '.txt' | |
// fs.existsSync(path) | |
// isFileReadable(path) | |
// isFileStat(path) | |
// isFileStatFast(path) | |
isFileStatFastSafe(path) | |
} | |
} | |
let delta = process.hrtime(timer) | |
console.log('took', format(delta)) | |
function isFileReadable(filename) { | |
try { | |
fs.accessSync(filename, fs.constants.R_OK) | |
return true | |
} catch { | |
return false | |
} | |
} | |
function isFileStat(filename) { | |
try { | |
fs.statSync(filename) | |
return true | |
} catch { | |
return false | |
} | |
} | |
function isFileStatFast(filename) { | |
return !!fs.statSync(filename, { throwIfNoEntry: false }) | |
} | |
const canRead = | |
fs.constants.S_IRUSR | fs.constants.S_IRGRP | fs.constants.S_IROTH | |
function isFileStatFastSafe(filename) { | |
const stat = fs.statSync(filename, { throwIfNoEntry: false }) | |
return stat ? !!(stat.mode & canRead) : false | |
} | |
function format(arr) { | |
let num = Math.round(arr[1] / 1e6) | |
if (arr[0] > 0) return (arr[0] + num / 1e3).toFixed(2) + 's' | |
return `${num}ms` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment