We talk about JavaScript. Each month in Warsaw, Poland.
JavaScript automatically allocates memory when objects are created.
Garbage collection - is a process of automatically freeing memory when those objects are no longer used.
Memory life-cycle:
Number
or String
).Object
& Array
- it also allocates memory for contained values.() => {}
) allocates a callable object (Function
).new Foo()
, new Date()
, etc.document.createElement( 'div' )
.array.concat( otherArray )
, 'JavaScript'.substr( 0, 4 )
,
...
The Garbage collector finds the memory which is no longer need.
All modern browsers uses the "mark-and-sweep" algorithm to detect objects that are no longer needed by finding "unreachable objects".
As of 2019 We cannot release memory manually (call the garbage collector).
But only if those are not needed by the application at given time. Otherwise those are valid objects.
window.performance.memory
to programmatically read used memory.Run your browser with all features striped down.
google-chrome \
--disable-extensions \
--disable-plugins \
--incognito
http://example.com
document.getElementById( 'ml-global' )
.addEventListener( 'click', () => {
// window.bo = new BigObject();
// bo = new BigObject();
this.bo = new BigObject(); // this === window
} );
const config = { bo: new BigObject(), foo: 'bar',
interval: 1000 };
logSomething( config );
function logSomething( config ) {
setInterval( () => { // Also: calback!
console.log( config.foo );
}, config.interval );
}
let theThing = null;
function replaceThing() {
const originalThing = theThing;
function unused() {
if ( originalThing ) {
// ...
}
}
theThing = {
bo: new BigObject(),
someMethod: function() {
// ...
}
};
}
const bo = new BigObject();
bo.node = document.getElementById( 'a-div' )
function detachNode() {
document.getElementById( 'a-div' ).remove(); // Removes from the DOM
}
setInterval( () => { // Interval is not cleared
console.log( bo[ 3 ] );
}, 500 );
console.log( bo ); // bo resides in console GC root
WeakMap
or WeakSet
.google-chrome -js-flags="--expose-gc"
- window.gc()
.