Memory profiling in Visual Studio 2013 with JsRT

One of the cool features of Visual Studio (starting in Visual Studio 2012 Update 1) is its JavaScript memory profiler. The profiler can take snapshots of the JavaScript heap and then gives you a nice UI you can use to drill in to those snapshots and compare them as you like:

Comparing two snapshots

Drilling in to a snapshot

Wouldn’t it be great to be able to utilize this to analyze the JavaScript memory usage in an app that hosts Chakra using JsRT? Well, you can! I’ve uploaded a new sample (and checked it in to my GitHub repo) that allows a JsRT app to generate heap dumps in a way that Visual Studio 2013 will be able to read. It doesn’t look quite as beautiful at the examples above–I didn’t go through the trouble of generating a screenshot for the summary page–but it should be entirely functional.

The sample project builds a C++ DLL that exports five functions:

  • bool InitializeMemoryProfileWriter() initializes the overall profile writer and should be called when you load the DLL.
  • MemoryProfileHandle StartMemoryProfile() starts a specific profile (called a “diagnostic session” in Visual Studio).
  • bool WriteSnapshot(MemoryProfileHandle memoryProfileHandle, IActiveScriptProfilerHeapEnum *enumerator) takes a memory profile handle and a heap enumerator (which can be obtained from JsEnumerateHeap) and writes the actual memory snapshot. Note that you can do this multiple times before finishing the memory profile. Each snapshot is written separately into the diagnostic session.
  • bool EndMemoryProfile(MemoryProfileHandle memoryProfileHandle, const wchar_t *filename) finishes the memory profile and writes it out to a file. The file should have a .diagsession extension if you want it to be natively recognized by VS when you open it. After this call, the memory profile handle is now invalid.
  • void ReleaseMemoryProfileWriter() releases the overall profiler writer and should be called when you’re shutting down or done with all profiling.

One thing to note is that once you’ve called JsEnumerateHeap for a particular JsRT runtime, you won’t be able to do anything in that runtime until the IActiveScriptProfilerHeapEnum pointer has been released.

We’ve already been using this code internally to look at the memory usage of some internal JsRT hosts, and it’s been very helpful! Let me know if there are problems or issues, and feel free to grab me on Twitter if you have any questions.

You should also follow me on Twitter here.

Leave a Reply

Your email address will not be published. Required fields are marked *