Home  >  Article  >  Web Front-end  >  Graphical introduction to JavaScript memory analysis in Chrome Developer Tools

Graphical introduction to JavaScript memory analysis in Chrome Developer Tools

黄舟
黄舟Original
2017-03-14 15:28:102212browse

Memory leak refers to the gradual reduction of the computer's available memory. It occurs when a program persistently fails to free the temporary memory it uses. JavaScript web applications also often encounter memory-related problems that occur in native applications, such as leaks and overflows. Web applications also need to deal with garbage collection pauses.

Although JavaScript uses garbage collection for automatic memory management, effective memory management is still important. In this article we will discuss analyzing memory issues in JavaScript web applications. As you learn about the features, be sure to try out the examples to increase your understanding of how these tools work in practice. Please read the Memory 101 page to familiarize yourself with the terminology used in this article. Note: Some of the features we are going to use are currently only available for the Chrome Canary version of the browser. We recommend using this version to get the best tools for analyzing your application's memory issues.

Questions you need to think about

Generally speaking, when you think you have encountered a memory leak problem, you need to think about three questions:

  • Does my page take up too much memory? - Timeline memory view tool (Timeline memory view) and Chrome task manager (Chrome task manager) can help you confirm whether you have used More memory. Memory view can track the DOM node count, documents document count and JSeventlistening count during page rendering. As a rule of thumb: avoid references to DOM elements you no longer need, remove unnecessary event listeners and be careful when storing large chunks of data that you may not use.

  • Does my page have a memory leak? - ObjectAllocation Tracking(Object allocation tracker) helps you locate leaks by viewing the allocation of JS objects in real time. You can also use the heap analyzer (Heap Profiler) to generate a JS heap snapshot, and find out the objects that have not been cleaned up by garbage collection by analyzing the memory map and comparing the differences between the snapshots.

  • How often is my page garbage collection forced? - If your page garbage collection is very frequent, it means that your page may be allocated too frequently. . Timeline memory view can help you find pauses of interest.

##Terminology and

Basic concepts

This section introduces

memory analysis Common terms used in memory analysis tools for other languages. The terms and concepts here are used in the Heap Profiler UI tool and related documentation.

These can help us become familiar with how to effectively use memory analysis tools. If you have ever used memory analysis tools for languages ​​like Java, .NET, etc., then this will be a

review.

Object sizes

Think of memory as a collection of basic types (like numbers and

strings) and objects (associative arrays ) chart. It might look something like the following diagram of a series of related points.

An object has two ways to use memory:

  • The object itself uses directly

  • Implicitly maintain references to other objects. This method will prevent garbage collection (GC) from automatically recycling those objects.

When you use the Heap Profiler in DevTools (Heap Profiler, a tool used to analyze memory problems, under the "Profile" tab of DevTools), you may be surprised to find Columns that display various information. Two of them are:

Direct memory occupation (Shallow Size) and Total memory occupation (Retained Size) , so what do they mean?

Directly occupy memory (Shallow Size, excluding the memory occupied by the referenced object)

This is the memory occupied by the object itself.

A typical JavaScript object will have reserved memory to describe the object and store its direct value. Generally, only arrays and strings will significantly occupy memory directly (Shallow Size). But strings and arrays often store the main data portion in renderer memory, only exposing a small wrapper object in the JavaScript object stack.

Renderer memory refers to all the memory used in the rendering process of the page you analyze: the memory of the page itself + the memory used by the JS heap in the page + the related worker processes (workers) triggered by the page The memory used by the JS heap. However, a small object may indirectly occupy a large amount of memory by preventing other objects from being automatically collected by the garbage.

Total memory occupied (Retained Size, including the memory occupied by the referenced object)

Once an object is deleted, the dependent objects it refers to cannot be ## When #GC root (GC root) is referenced, the memory occupied by them will be released. The total memory occupied by an object includes the memory occupied by these dependent objects.

GC root is composed of controllers(handles). These controllers (whether local or global) is created when establishing a reference from the build-infunction(native code) to a JavaScript object outside the V8 engine. All of these controllers have access to the GC roots(GC roots) > Handle scope and GC roots >Global handlers## of the heap snapshot Found in #. Introducing these controllers in this article may be confusing without a deep understanding of browser implementation. You don't need to worry too much about GC roots and controllers. There are many internal GC roots that are unimportant to users. From an application perspective, there are the following situations:

    Window global object (all in
  • if

    rame). There is a distance field in the heap snapshot, which is the shortest path length from the window object to the corresponding object.

  • The document DOM tree consists of all DOM nodes that the document can traverse. Not all nodes will be referenced by the corresponding JS, but the nodes referenced by JS will be retained as long as the document exists.
  • There are many objects that may be created when
  • debugging

    code or in the DevTools console (for example: after some code in the console is executed).

Note:

We recommend that users do not execute code in the console or enable debugging breakpoints when creating heap snapshots. The memory map starts with a root, which may be the browser's

window

object or the Node.jsmoduleGlobal object. How these objects are reclaimed from memory is not under the user's control.

Objects that cannot be traversed by the GC root will be memory recycled.

Note:

The data in the directly occupied memory and total memory occupied fields are expressed in bytes. Total memory tree occupied by objects

We have learned before that the heap is a network structure composed of various interrelated objects. In the digital world, this structure is called a graph or memory graph. The graph is composed of

nodes

connected by edges, and they are all labeled.

Nodes
    (
  • or object

    ) The label names of nodes are determined by the constructor## that created them. #Determine the name of the functionEdges

    The tag name is
  • Attribute
  • Name

    ## Later in this document you will learn how to use the Heap Analyzer to generate snapshots. From the snapshot generated by the heap analyzer in the figure below, we can see the distance field: it refers to the distance from the object to the GC root. If all objects of the same type are at the same distance, but a small subset are farther apart, there may be something wrong that you need to investigate.

  • Dominators

    Dominator objects are like a tree structure because each object has a Dominator. The controller of an object may not directly refer to the object it dominates, that is, the dominated object tree structure is not a spanning tree in the graph.

    In the above diagram:

    • Node 1 dominates Node 2

    • Node 2 dominates nodes 3, 4 and 6

    • node 3 dominates node 5

    • node 5 dominates node 8

    • Node 6 dominates node 7

    In the example below, node #3 is the dominant node of #10, but #7 also appears in every path from GC to #10. Like this, if the B object appears in every path from the root node to the A object, then the B object is the dominant object of the A object.

    V8 Introduction

    In this section, we will describe some memory-related concepts that are related to the V8 JavaScript Virtual Machine (V8 VM or VM) related. When analyzing memory, it is helpful to understand these concepts in order to understand heap snapshots.

    JavaScript Object Description

    There are three primitive types:

    • Numbers (such as 3.14159..)

    • Booleans (true or false)

    • Character type (Strings) (such as 'Werner Heisenberg')

    They will not reference other values, they will only be leaf nodes or terminal nodes.

    Numbers are stored in one of two ways:

    • 31-bit Integersdirect values, Called: small integers (small integers)(SMIs), or

    • heap objects, referenced as Heap value. Heap values ​​are used to store data that are not suitable for SMI storage, such as double numbers, or when a value needs to be boxed, such as this value and then set the attribute value.

    Character typeData will be stored in the following two ways:

    • VM heap, Or

    • external renderer memory. At this time, a wrapper object is created to access the storage location, such as script resources and other content stored in the web page package, instead of being copied directly to the VM heap.

    Newly created JavaScript objects will be allocated memory on the JavaScript heap (or VM heap). These objects are managed by V8's garbage collector and will remain in memory as long as there is a strong reference to them.

    Local objects are all objects that are not in the JavaScript heap. Unlike heap objects, they will not be garbage collected by V8 during their lifecycle The handler can only wrap object references through JavaScript.

    Connection string is an object formed by merging a pair of strings, and is the result of the merging. Connection stringsMerge only when necessary. Like a concatenated string substring needs to be constructed.

    For example: if you connect a and b, you get the string (a, b) which is used to represent the result of the connection. If you later concatenate this result with d, you get another concatenation string ((a, b), d).

    Array (Arrays) - Array is an object with numeric keys. They are widely used in the V8 engine when storing large amounts of data. Objects with key-value pairs like dictionaries are implemented using arrays.

    A typical JavaScript object can be stored in one of two array types:

    • named properties, and

    • Number elements

    If there are only a few properties, they will be stored directly in the JavaScript object itself.

    Map - An object used to describe an object type and its structure. For example, maps will be used to describe the structure of objects to achieve quick access to object properties

    Object Group

    Each local object group is composed of a group of interrelated objects of. For example, in a DOM subtree, each node can access its parent element, the next child element, and the next sibling element, which form an association graph. Note that native elements are not represented in the JavaScript heap - that's why their size is zero while their wrapping object is created.

    Each wrapper object will have a reference to a local object, which is used to pass operations on these local objects. These local objects also have references to the wrapped objects. But this does not create an irrecoverable cycle, the GC is smart enough to identify local objects that no longer refer to the wrapped object and release them. But if a wrapper object is not released, it will retain all object groups and related wrapper objects.

    Prerequisites and Helpful Tips

    Chrome Task Manager

    Note: When using Chrome for memory profiling, it is best to set up a clean test Environment

    Open Chrome's memory manager, observe the memory field, and perform related operations on a page. You can quickly determine whether this operation will cause the page to occupy a lot of memory. You can find Memory Manager from Chrome Menu > Tools or by pressing Shift + Esc.

    After opening, right-click on the header and select the memory used by JavasScript item.

    Locate memory problems through DevTools Timeline

    The first step in solving the problem is to be able to prove that the problem exists. This requires creating a reproducible test that serves as a baseline measure of the problem. Without reproducible procedures, the problem cannot be measured reliably. In other words, without a baseline for comparison, there is no way to know what changes caused the problem.

    Timeline panelIt is very helpful to find when there is a problem with the program. It shows the moments when your web application or website is loading and interacting. All events: from loading resources to decoding JavaScript, style calculations, garbage collection pauses and page repaints. All are represented on the timeline.

    When analyzing memory problems, the MemoryView(Memory view) on the timeline panel can be used to observe:

    • Total memory used – Has memory usage increased?

    • Number of DOM nodes

    • Number of documents

    • Number of registered event listeners

    More about locating memory during memory analysis For leaks, see Zack Grossbart's Memory profiling with the Chrome DevTools

    Proving the existence of a problem

    The first thing to do is to find out what you think may be causing the problem Some actions for memory leaks. This can be any event that occurs on the page, including mouseovers, clicks, or other interactions that may cause performance degradation on the page.

    Start recording in the timeline panel (Ctrl+E or Cmd+E) and then make the action you want to test. To force garbage collection, click the trash can icon () on the panel.

    Here is an example of a memory leak where some points are not garbage collected:

    If after some repeated testing, you see jagged The graphic (above the memory panel) indicates that there are many short-lived objects in your program. And if a series of actions do not keep the memory within a certain range, and the number of DOM nodes does not return to the number at the beginning, you can suspect a memory leak.

    Once you have determined that there is a memory problem, you can use the heap analyzer on the Profiles panel profiler) to locate the source of the problem.

    Example: Try the memory growth example, which can help you effectively Practiceanalyze memory problems through the timeline.

    Memory Recycling

    The memory collector (like in V8) needs to be able to locate which objects are live(live), and which objects are The object that is dead(garbage) is unreferenceable(unreachable).

    If Garbage Collection (GC) fails to collect garbage objects due to logic errors in JavaScript execution, these garbage objects can no longer be recycled. Situations like this will eventually make your application slower and slower.

    For example, when you are writing code, some variables and event listeners are no longer used, but they are still referenced by some codes. As long as the reference still exists, the referenced object cannot be correctly recycled by GC.

    While your application is running, some DOM objects may have been updated/removed. Remember to check for variables that reference DOM objects and set them ##null. Check object properties that may reference other objects (or other DOM elements). Keep an eye on the variablescaching that may grow more and more.

    Heap Analyzer

    Take a Snapshot

    In the Profiles panel, select Take Heap Snapshot and click Start or Press Cmd + E or Ctrl + E:

    #The snapshot is initially saved in the renderer process memory. They are imported into DevTools on demand and you can see them when you click the Snapshotbutton. When a snapshot is loaded into DevTools and displayed, the number below the snapshot title shows the total amount of memory occupied by reachable JavaScript objects.

    Example: Try the example of garbage collection in action and monitor memory usage in the Timeline panel.

    Clear snapshots

    Click Clear allbutton icon() to clear all snapshots:

    Note: Close the DevTools window does not delete the collected snapshots from the rendering memory. When DevTools is reopened, the previous snapshot list is still there.

    Remember what we mentioned before, you can force GC in DevTools when you take a snapshot. When we take a snapshot, GC is executed automatically. You can easily perform garbage collection by clicking the trash can (garbage collection) button () in the Timeline.

    Example: Try scattered objects and analyze it with Heap Profiler. You can see the collection of (object) items.

    Switch snapshot view

    A snapshot can switch views according to different tasks. You can switch through the selection box as shown in the figure:

    The following are three default views:

    • Summary (Summary) - Display objects by constructor name classification;

    • Comparison - Display the differences between objects between two snapshots;

    • Containment - Can be used to detect the contents of the heap;

    ##DominatorsThe view can be opened in the Settings panel - displays the dominators tree. It can be used to find memory growth points.

    Distinguish objects through different colors

    The attributes and attribute values ​​of objects have different types and are automatically distinguished by color. Each property is one of the following four:

    • a:property - an ordinary property indexed by the name , represented by .(dot )operator, or [] (square bracket) reference, such as ["foo bar"];

    • 0:element

      - Pass Ordinary properties with numerical indexes, referenced by [] (square brackets);

    • a:context var

      - properties within a function, within the function context, by name Quote;

    • a:system prop

      - A property added by the JavaScript VM and cannot be accessed by JavaScript code.

    • The object named
    System

    has no corresponding JavaScript type. They are built into the JavaScript VM object system. V8 places most built-in objects and user JS objects in the same heap. But they are just V8's internal objects. View details

    Summary view

    Open a snapshot, which is displayed in summary view by default. It displays the total number of objects and can be expanded to display specific content: Initially , a snapshot opens in the Summary view,

    display

    ing object totals, which can be expanded to show instances:

    The first level is the "overall" row, they show:

    After expanding an overall row, all object instances will be displayed. The direct memory occupied and the total memory occupied by each instance are displayed accordingly. The number after the @ symbol is the unique ID of the object. With it, you can compare between different snapshots on an object-by-object basis.

    Example: Try this example (opens in a new tab) to learn how to use the summary view.

    Remember that yellow objects are referenced by JavaScript, while red objects are referenced by detached nodes with a yellow background color.

    Comparison view

    This view is used to compare different snapshots to find the differences between snapshots and to find objects with memory leaks. To prove that a certain operation of the application does not cause leakage (for example: generally a pair of operations and undo actions, such as opening a document and then closing it, will not cause leakage), you can try the following steps:

    1. Take a heap snapshot before the operation;

    2. Perform an operation (do the action you think will cause a leak);

    3. Undo the previous operation (reverse the previous operation and repeat it several times);

    4. Take a second snapshot and switch the view to the control view. And compare with snapshot 1.

    In comparison view, the differences between the two snapshots will be displayed. When a general category is expanded, added and deleted objects are displayed:

    Example: Try the example (open in a new tab) to learn how to use it Check views to locate memory leaks.

    Containment view

    The control view can be called a “bird’s eye view” of your application’s object structure. It allows you to look inside functions, just like your JavaScript objects, inside VM objects, giving you a very low-level view of memory usage in your application.

    This view provides several entry points:

    • DOMWindow Objects - These objects are the "global" objects for JavaScript code;

    • GC root - The real GC root of the VM's garbage collector;

    • Native object - Browse The object is "pushed" into the JavaScript virtual machine to perform automatic operations, such as: DOM nodes, CSS rules (details will be introduced in the next section.)

    The following figure is a typical Control view:

    Example: Try the example (open in a new tab) to see how to use a control view to see internals and## of closures ##Event handling.

    Tips on Closures

    It can be helpful to name your functions to help you differentiate between closure functions in a snapshot. For example: the following example does not name the function:

    function createLargeClosure() {
      var largeStr = new Array(1000000).join('x');
    
      var lC = function() { // this is NOT a named function
        return largeStr;
      };
    
      return lC;
    }

    and the following example does name the function:

function createLargeClosure() {
  var largeStr = new Array(1000000).join('x');

  var lC = function lC() { // this IS a named function
    return largeStr;
  };

  return lC;
}

Example: Try this example why eval is evil to analyze the impact of closures in memory. You may also be interested in trying the following example of logging heap allocations.

Expose DOM memory leaks

The unique thing about this tool is that it shows the bidirectional references between browser native objects (DOM nodes, CSS rules) and JavaScript objects. This can help you find subtle memory leaks caused by forgetting to dereference a free DOM child node.

DOM memory leaks may occur beyond your imagination. Look at the following example - when is the #tree object GCed?

var select = document.querySelector;
  var treeRef = select("#tree");
  var leafRef = select("#leaf");
  var body = select("body");

  body.removeChild(treeRef);

  //#tree can't be GC yet due to treeRef
  treeRef = null;

  //#tree can't be GC yet due to indirect
  //reference from leafRef

  leafRef = null;
  //#NOW can be #tree GC

#leaf

represents a reference to its parent node (parentNode) which recursively refers to #tree, so only when After leafRef is nullified, the entire tree structure represented by #tree will be recycled by GC.

Example: Try leaking DOM nodes to understand where DOM nodes will leak memory and how to locate it. You can also look at this example: DOM leaks being bigger than expected.

Check out Gonzalo Ruiz de Villa’s article Finding and debugging memory leaks with the Chrome DevTools to read more about DOM memory leaks and the basics of memory analysis.

Native objects are easier to find in Summary and Containment views – they have their own categories:

Example: Try this example (in the new tab) to learn how to separate the DOM tree.

Dominators view

The Dominators view displays the Dominators tree of the stack graph. The Dominator view is similar to the Containment view, but does not have property names. This is because the ruler may be an object that does not have a direct reference, which means that the ruler tree is not a spanning tree of the heap graph. But this is a useful view that can help us quickly locate memory growth points.

Note: In Chrome Canary, the Dominator view can be turned on in Settings > Show advanced heap snapshot properties in DevTools and will take effect after restarting DevTools.

Example: Try this example (open in a new tab) to practice finding memory growth points. You can try the next example of retaining paths and dominators further.

Object Allocation Tracker

Object TrackerIntegrate the snapshot incremental update analysis of the heap profiler and the recording of the Timeline panel. Like other tools, recording an object's heap configuration requires starting recording, performing a series of operations, then stopping recording and analyzing it.

The object tracker continuously records heap snapshots (frequency reaches every 50 milliseconds!), and records the last snapshot at the end. The heap allocation analyzer shows where an object was created and its reserved path.

Open and use Object Analyzer

Start using Object Analyzer: 1. Make sure you are using the latest version of Chrome Canary.

  1. Open DeveTools and click on the gear icon (Translator: I don’t understand the use of this step).

  2. Now, open the Profiler panel and you will see the "Record Heap Allocations" option.

The bars above represent new objects generated in the heap. The height corresponds to the size of the corresponding object, and its color indicates whether the object is still there in the last snapshot taken: the blue column indicates that the object is still there at the end of the timeline, and the gray column indicates that the object was generated in the timeline, but The memory has been reclaimed before ending.

In the above example, an action is executed 10 times. The same program retains 5 objects, so the last 5 blue bars are retained. But there are potential problems with the last remaining column. You can use the slider on the timeline to zoom in to that specific snapshot and find the allocated object.

#Clicking on an object in the heap displays its total reserved memory tree in the lower part of the heap snapshot. Examining the total reserved memory tree for this object can give you enough information to understand why this object has not been collected, and you can then make appropriate changes to your code to remove unnecessary references.

Memory Analysis FAQ

Q: I cannot see all properties of an object, I also see their non-string values! Why?

Not all properties are completely saved in the JavaScript heap. Some of them are obtained by executing getters methods of native code. These properties are not captured in the heap snapshot to prevent calls to getters and avoid changes to the program's state if those getters are not "pure" functions. Likewise, non-string values, such as numbers, are not captured to reduce the size of the snapshot. Q: What does the number after the @

symbol mean – is it an address or an ID? Is this ID value really unique?

This is the object ID. Displaying the address of an object is meaningless because an object will be removed during garbage collection. These object IDs are real IDs - that is, they are uniquely represented between different snapshots. This allows for accurate comparison between heap states. Maintaining these IDs adds additional overhead to the GC process, but this is only allocated when the first heap snapshot is recorded - if the heap analyzer is not used, there is no additional overhead.

Q: Are "dead" (unreferenced) objects included in the snapshot?

No, only objects that can be referenced will be displayed in the snapshot. Moreover, GC operations will be automatically performed before taking a snapshot.

Note: At the time of writing this article, we plan to no longer GC when taking snapshots to prevent the heap size from being reduced. This is now the case, but the garbage objects still show up outside the snapshot.

Q: What does the GC root consist of?

is composed of many parts Group into:

  • Native object graph;

  • symbols Table;

  • Stack in VM thread;

  • Edit cache;

  • Controller context ;

  • Global controller.

Q: I learned that I can use Heap Profiler and Timeline Memory view to detect memory leaks. But which tool should I use first?

The Timeline panel is used to diagnose excessive memory usage when you first use your page and find it slows down. A slow website is a classic sign of a memory leak, but it can also be for other reasons - there could be a rendering or network bottleneck, so make sure you address the real problem with your page.

To determine whether it is a memory problem, open the Timeline panel and the Memory tab. Click the record button and repeat the operation on your application several times that you think may cause a memory leak. Stop recording. The memory usage graph of your application is generated. If memory usage keeps increasing (without a corresponding decrease), this is a sign that your application may have a memory leak.

Generally, the memory usage graph of a normal application is jagged, because the memory will be reclaimed by the garbage collector after being used. Don't worry about this aliasing - there will always be memory consumption due to JavaScript, and even an empty requestAnimationFrame will cause this aliasing, which is unavoidable. As long as it is not a shape that allocates a lot of continuous memory, it means that a lot of memory garbage is generated.

The growth line in the above picture requires you to be wary. The DOM node counter, Document counter and Event listener count in the Memory tag are also very useful during diagnostic analysis. The number of DOM nodes is the native memory used and does not affect the JavaScript memory map.

#Once you confirm that your application has a memory leak, a heap analyzer can be used to find the memory leak.

Question: I found that the numbers of some DOM nodes in the heap snapshot are marked in red as "Detached DOM tree", while others are in yellow. What does this mean?

You will find there are different colors. The red nodes (with dark backgrounds) have no direct reference to them from JavaScript, but they are part of a separate DOM structure, so they remain in memory. It's possible that a node is referenced by JavaScript (perhaps in a closure or a variable), and this reference prevents the entire DOM tree from being reclaimed.

Yellow nodes (yellow background) have direct references to JavaScript. Look for a yellow node in the same detached DOM tree to locate your JavaScript references. It is possible to see the attribute reference chain from the DOM window to that node (such as: window.foo.bar[2].baz).

The dynamic diagram below shows the process of detached nodes:

Example: Try this example detached nodes and you can view the nodes Life cycle in Timeline, and then take a heap snapshot to find the separated nodes.

Q: What do directly occupied memory (Shallow Size) and occupied total memory (Retained Size) represent respectively, and what is their difference?

This is the case, objects can exist in memory in two ways (be alive) - directly retained by another accessible (alive) object (window and document objects are always accessible ) or implicitly contained references by native objects (like DOM objects). The latter method may cause memory leaks by preventing objects from being automatically recycled by GC. The memory occupied by the object itself is called direct memory (generally speaking, arrays and strings will reserve more direct memory (shallow size)).

An object of any size can preserve large memory usage by preventing other objects' memory from being reclaimed. When an object is deleted (some of the dependencies it creates can no longer be referenced), the amount of memory that can be released is called the total memory occupied (retained size).

Q: There is a lot of data under the constructor and retained fields. Where should I start to investigate whether I am experiencing a memory leak?

Generally speaking, it is best to start from the first object sorted by retainers. The retainers are sorted by distance (referring to the distance to the window object).

#The object with the shortest distance may be the preferred object that may cause a memory leak.

Q: What is the difference between Summary, Comparison, Dominators and Containment views?

You can experience their differences by switching views.

  • The Summary view helps you find objects (and their memory usage) grouped by constructors. This view is helpful for finding DOM memory leaks.

  • The Comparison view can search for memory leaks by showing which objects' memory was correctly reclaimed. Typically two (or more) memory usage snapshots are recorded before and after an operation. It checks whether there is a memory leak by looking at the difference between the released memory and the number of references, and finds the cause.

  • The Containment (Control) view has a better display of the object structure and helps us analyze the object references in the global scope (such as window) to find out what retains these objects. It allows you to analyze closures and drill down deeper into objects.

  • The Dominators view can be used to help us confirm that no redundant objects are still hanging in a certain location (such as those that are referenced), and to confirm the deletion/trash of objects Recycling really makes a difference.

Q: What does the content of the constructor (a group) in the heap analyzer represent?

  • (global property) - between a global object (like 'window') and objects that reference it intermediate object. If an object is generated by the constructor Person and is referenced by the global object, the reference path is like this: [global] > (global property) > Person. This is different from objects that directly reference each other. We use intermediate objects for performance reasons. Global objects change frequently, and the attribute access optimization of non-global variables does not apply to global variables.

  • (roots) - The content of roots in the constructor refers to the object it selects. They can also be references created autonomously by the engine. This engine has a cache for referenced objects, but these references do not prevent the referenced object from being recycled, so they are not truly strong references (FIXME).

  • (closure) - A reference to a set of objects in some function closure

  • (array, string, number, regexp) - A set of properties referencing an object type of Array, String, Number or regular expression

  • (compiled code) - Simply put, everything is related to compiled code. Script is like a function, but actually corresponds to the content of 3f1c4e4b6b16bbbd69b2ee476dc4f83a. SharedFunctionInfos (SFI) are objects between functions and compiled code. Functions usually have content, SFIS does not (FIXME).

  • ##HTMLpElement, HTMLAnchorElement, DocumentFragment, etc. – references to elements or document objects in your code .

Many other objects generated during the life cycle of your program, including event listeners or custom objects, can be found in the following controllers:

Q: Do I need to turn off any functions in Chrome that may have an impact when doing memory analysis?

We recommend that when using Chrome DevTools for memory analysis, you can use incognito mode with all extensions turned off, or set the user folder to (

--user-data-dir=" ") and then open Chrome.

Applications, extensions and even records in the console will have a potential impact on your analysis. If you want your analysis to be reliable, disable these.

Write the words at the end

Today's JavaScript engines already have strong capabilities and can automatically recycle memory garbage generated by code. That is, they can only do so much, but our application is still proven to produce memory leaks due to logical errors. Use the appropriate tools to find your application's bottlenecks, and remember, don't guess - test it.

Help examples

Diagnosing memory leaks

Although a lot of the content has been mentioned in this article, a series of examples for testing memory-related problems are still very useful, below is a set of examples of DOM node memory leaks. You may want to experiment with these examples before testing your more complex pages or applications.

  • Example 1: Growing memory

  • Example 2: Garbage collection in action

  • Example 3 : Scattered objects

  • Example 4: Detached nodes

  • Example 5: Memory and hidden classes

  • Example 6: Leaking DOM nodes

  • Example 7: Eval is evil (almost always)

  • Example 8 : Recording heap allocations

  • Example 9: DOM leaks bigger than expected

  • Example 10: Retaining path

  • Example 11: Last exercise

The above is the detailed content of Graphical introduction to JavaScript memory analysis in Chrome Developer Tools. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn