Perf improvement to stat in jest-resolve
See original GitHub issue🐛 Bug Report
jest-resolve
specified its own isFile
and isDirectory
. stat[Sync]
does some weird stuff by capturing a very large stack trace on failure (see here). Based on what we need from the errors of statSync
for resolving, we dont need these stack traces (as errors when resolving are much more “expected”). My proposal below should improve resolving performance (with included rough console.time numbers):
To Reproduce
Create a “simulated” resolve environment (just forcing a lot of failed stat calls)
const fs = require("fs");
function oldStat(path) {
let stat;
try {
stat = fs.statSync(path);
} catch (e) {
if (!(e && (e.code === "ENOENT" || e.code === "ENOTDIR"))) {
throw e;
}
}
}
console.time("oldStat");
for (let i = 0; i < 100000; i++) oldStat("not-real-path");
console.timeEnd("oldStat");
# Console output
oldStat: 8.336s
Expected behavior
If we prevent capturing these extended traces, we see much improved CPU time for these stat calls.
function newStat(path) {
let stat;
let oldTrace = Object.getOwnPropertyDescriptors(Error).stackTraceLimit;
try {
Object.defineProperty(Error, "stackTraceLimit", {
value: 0,
writable: false,
});
stat = fs.statSync(path);
} catch (e) {
if (!(e && (e.code === "ENOENT" || e.code === "ENOTDIR"))) {
throw e;
}
} finally {
Object.defineProperty(Error, "stackTraceLimit", oldTrace);
}
}
console.time("newStat");
for (let i = 0; i < 100000; i++) newStat("not-real-path");
console.timeEnd("newStat");
# Console output
newStat: 5.014s
Is there any interest in this change? If so, I can make a simple PR to get this going. Apologies if this doesnt dall in “bug” work item type, but didnt think it was a feature either.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
This only affects statSync. In very recent node.js versions there is an option to return undefined instead of throwing an error on not found
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.