Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
memory.qdoc
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3/*!
4
5\page qtqml-javascript-memory.html
6\title Memory Management in the JavaScript Engine
7\brief Describes how the JavaScript Engine manages memory.
8
9\section1 Introduction
10
11This document describes the \e dynamic memory management of the JavaScript
12Engine in QML. It is a rather technical, in depth description. You only need
13to read this if you care about the exact characteristics of JavaScript memory
14management in QML. In particular, it can be helpful if you're trying to
15optimize your application for maximum performance.
16
17\note By compiling your QML code to C++ using the \l{Qt Quick Compiler}
18you can avoid much of the JavaScript heap usage. The generated C++ code uses the
19familiar C++ stack and heap for storing objects and values. The
20\l{JavaScript Host Environment}, however, always uses some JavaScript-managed
21memory, no matter if you use it or not. If you use features that cannot be
22compiled to C++, the engine will fall back to interpretation or JIT compilation
23and use JavaScript objects stored on the JavaScript heap, though.
24
25\section1 Basic Principles
26
27The JavaScript engine in QML has a dedicated memory manager that requests
28address space in units of multiple pages from the operating system. Objects,
29strings, and other managed values created in JavaScript are then placed in this
30address space, using the JavaScript engine's own allocation scheme. The
31JavaScript engine does not use the C library's malloc() and free(), nor the
32default implementations of C++'s new and delete to allocate memory for
33JavaScript objects.
34
35Requests for address space are generally done with mmap() on Unix-like systems
36and with VirtualAlloc() on windows. There are several platform-specific
37implementations of those primitives. Address space reserved this way is not
38immediately committed to physical memory. Rather, the operating system notices
39when a page of memory is actually accessed and only then commits it. Therefore,
40the address space is practically free and having a lot of it gives the
41JavaScript memory manager the leverage it needs to place objects in an efficient
42way on the JavaScript heap. Furthermore, there are platform-specific techniques
43to tell the operating system that a chunk of address space, though still
44reserved, does not have to be mapped into physical memory for the time being.
45The operating system can then decommit the memory as needed and use it for other
46tasks. Crucially, most operating systems do not guarantee immediate action on
47such a decommit request. They will only decommit the memory when it is actually
48needed for something else. On Unix-like systems we generally use madvise() for
49this. Windows has specific flags to VirtualFree() to do the equivalent.
50
51\note There are memory profiling tools that do not understand this mechanism and
52over-report JavaScript memory usage.
53
54All values stored on the JavaScript heap are subject to garbage collection.
55None of the values are immediately "deleted" when they go out of scope or are
56otherwise "dropped". Only the garbage collector may remove values from the
57JavaScript heap and return memory (see \l{Garbage Collection} below for how
58this works).
59
60\section1 QObject-based Types
61
62QObject-based types, and in particular everything you can phrase as a QML
63element, are allocated on the C++ heap. Only a small wrapper around the pointer
64is placed on the JavaScript heap when a QObject is accessed from JavaScript.
65Such a wrapper, however, can own the QObject it points to. See
66\l{QJSEngine::ObjectOwnership}. If the wrapper owns the object, it will be
67deleted when the wrapper is garbage-collected. You can then also manually
68trigger the deletion by calling the destroy() method on it. destroy() internally
69calls \l{QObject::deleteLater()}. It will therefore not immediately delete the
70object, but wait for the next event loop iteration.
71
72QML-declared \e properties of objects are stored on the JavaScript heap. They
73live as long as the object they belong to lives. Afterwards they are removed the
74next time the garbage collector runs.
75
76\section1 Object Allocation
77
78In JavaScript, any structured type is an object. This includes function objects,
79arrays, regular expressions, date objects and much more. QML has a number of
80internal object types, such as the above mentioned QObject wrapper. Whenever
81an object is created, the memory manager locates some storage for it on the
82JavaScript heap.
83
84JavaScript strings are also managed values, but their string data is not
85allocated on the JavaScript heap. Similar to QObject wrappers, the heap objects
86for strings are just thin wrappers around a pointer to string data.
87
88When allocating memory for an object, the size of the object is first rounded up
89to 32 byte alignment. Each 32 byte piece of address space is called a "slot".
90For objects smaller than a "huge size" threshold, the memory manager performs
91a series of attempts to place the object in memory:
92\list
93\li The memory manager keeps linked lists of previously freed pieces of heap,
94 called "bins". Each bin holds pieces of heap with a fixed per-bin size in
95 slots. If the bin for the right size is not empty, it picks the first entry
96 and places the object there.
97\li The memory that hasn't been used yet is managed via a bumper allocator. A
98 bumper pointer points to the byte beyond the occupied address space. If
99 there is still enough unused address space, the bumper is increased
100 accordingly, and the object is placed in unused space.
101\li A separate bin is kept for previously freed pieces of heap of varying sizes
102 larger than the specific sizes mentioned above. The memory manager
103 traverses this list and tries to find a piece it can split to accommodate
104 the new object.
105\li The memory manager searches the lists of specifically sized bins
106 larger than the object to be allocated and tries to split one of those.
107\li Finally, if none of the above works, the memory manager reserves more
108 address space and allocates the object using the bumper allocator.
109\endlist
110
111Huge objects are handled by their own allocator. For each of those one or more
112separate memory pages are obtained from the OS and managed separately.
113
114Additionally, each new chunk of address space the memory manager obtains from
115the OS gets a header that holds a number of flags for each slot:
116\list
117\li \e{object}: The first slot occupied by an object is flagged with this bit.
118\li \e{extends}: Any further slots occupied by an object are flagged with this
119 bit.
120\li \e{mark}: When the garbage collector runs, it sets this bit if the object is
121 still in use.
122\endlist
123
124\section1 Internal Classes
125
126In order to minimize the required storage for metadata on what members
127an object holds, the JavaScript engine assigns an "internal class" to each
128object. Other JavaScript engines call this "hidden class" or "shape".
129Internal classes are deduplicated and kept in a tree. If a property is
130added to an object, the children of the current internal class are checked to
131see if the same object layout has occurred before. If so, we can use the
132resulting internal class right away. Otherwise we have to create a new one.
133
134Internal classes are stored in their own section of the JavaScript heap that
135otherwise works the same way as the general object allocation described above.
136This is because internal classes have to be kept alive while the objects using
137them are collected. Internal classes are then collected in a separate pass.
138
139The actual property attributes stored in internal classes are \e not kept on
140the JavaScript heap, though, but rather managed using new and delete.
141
142\section1 Garbage Collection
143
144The garbage collector used in the JavaScript engine is a non-moving,
145stop-the-world Mark and Sweep design. In the \e mark phase we traverse all the
146known places where live references to objects can be found. In particular:
147
148\list
149\li JavaScript globals
150\li Undeletable parts of QML and JavaScript compilation units
151\li The JavaScript stack
152\li The persistent value storage. This is where QJSValue and similar classes
153 keep references to JavaScript objects.
154\endlist
155
156For any object found in those places the mark bits are set recursively for
157anything it references.
158
159In the \e sweep phase the garbage collector then traverses the whole heap and
160frees any objects not marked before. The resulting released memory is sorted
161into the bins to be used for further allocations. If a chunk of address space
162is completely empty, it is decommitted, but the address space is retained
163(see \l{Basic Principles} above). If the memory usage grows again, the same
164address space is re-used.
165
166The garbage collector is triggered either manually by calling the \l [QML] {Qt::}{gc()} function
167or by a heuristic that takes the following aspects into account:
168
169\list
170\li The amount of memory managed by object on the JavaScript heap, but not
171 directly allocated on the JavaScript heap, such as strings and internal
172 class member data. A dynamic threshold is maintained for those. If it is
173 surpassed, the garbage collector runs and the threshold is increased. If
174 the amount of managed external memory falls far below the threshold, the
175 threshold is decreased.
176\li The total address space reserved. The internal memory allocation on the
177 JavaScript heap is only considered after at least some address space has
178 been reserved.
179\li The additional address space reservation since the last garbage collector
180 run. If the amount of address space is more than double the amount of
181 used memory after the last garbage collector run, we run the garbage
182 collector again.
183\endlist
184
185\section1 Analyzing Memory Usage
186
187In order to observe the development of both the address space and the number
188of objects allocated in it, it is best to use a specialized tool. The
189\l{Qt Creator: QML Profiler}{QML Profiler} provides a visualization that
190helps here. More generic tools cannot see what the JavaScript memory manager
191does within the address space it reserves and may not even notice that part
192of the address space is not committed to physical memory.
193
194Another way to debug memory usage are the
195\l{QLoggingCategory}{logging categories} \e{qt.qml.gc.statistics} and
196\e{qt.qml.gc.allocatorStats}. If you enable the \e{Debug} level for
197qt.qml.gc.statistics, the garbage collector will print some information every
198time it runs:
199
200\list
201\li How much total address space is reserved
202\li How much memory was in use before and after the garbage collection
203\li How many objects of various sizes were allocated so far
204\endlist
205
206The \e{Debug} level for qt.qml.gc.allocatorStats prints more detailed
207statistics that also include how the garbage collector was triggered, timings
208for the mark and sweep phases and a detailed breakdown of memory usage by bytes
209and chunks of address space.
210
211*/