DEV Community

Cover image for Visualize Performance issues in your JavaScript application
Darshan Sen
Darshan Sen

Posted on

Visualize Performance issues in your JavaScript application

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!

Tracing requires using perftrace

The code for this example is available here.

How do I use it?

Install it:

npm i perftrace
Enter fullscreen mode Exit fullscreen mode

Create a new TraceEvents object:

const { TraceEvents } = require("perftrace");
const traceEvents = new TraceEvents(); 
Enter fullscreen mode Exit fullscreen mode

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));
});
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

To trace require() calls, simply call trackRequires(true):

const { trackRequires } = require("perftrace");
trackRequires(true);
Enter fullscreen mode Exit fullscreen mode

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)