While working on improving the performance of an Electron app, I noticed that it was require()
-ing a lot of modules up front during startup, which was leading to a poor startup performance. However, it was hard to tell which modules were taking the most time to load. So I decided to create perftrace
to visualize performance issues in your JavaScript application!
What is perftrace
?
Record PerformanceEntry objects from your JavaScript application in the Trace Event Format, so that it can be visualized on https://ui.perfetto.dev like this!
The code for this example is available here.
How do I use it?
Install it:
npm i perftrace
Create a new TraceEvents
object:
const { TraceEvents } = require("perftrace");
const traceEvents = new TraceEvents();
Attach a callback to generate a file with the traces before the process exits:
const { writeFileSync } = require("node:fs");
process.on("beforeExit", () => {
const events = traceEvents.getEvents();
traceEvents.destroy();
writeFileSync("events.json", JSON.stringify(events));
});
Profile the parts of your application that you are interested in by using the performance.mark()
and performance.measure()
Web APIs:
// Only needed in Node.js:
const { performance } = require("node:perf_hooks");
// `performance` is a global Web API present in other JavaScript runtimes.
performance.mark("before");
// code that needs to be measured
performance.measure("after", "before");
To trace require()
calls, simply call trackRequires(true)
:
const { trackRequires } = require("perftrace");
trackRequires(true);
Run your program. After it stops, the generated file can be opened on https://ui.perfetto.dev for visualization.
Conclusion
Check out the project repository here. Go through the API documentation and try out these examples!
If you find this useful, please consider supporting my work in https://github.com/sponsors/RaisinTen.
Top comments (0)