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