JavaScript Memory Management Masterclass

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Memory Management Masterclass

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Foundation

const memoryUsed = () =>
Math.floor(process.memoryUsage().heapUsed / (1e6)) + ' MB';

const collectGarbage = () => {
const before = process.memoryUsage().heapUsed;
global.gc();
const after = process.memoryUsage().heapUsed;
console.log(`Garbage Collected: ${Math.floor((before - after) / 1e6)} MB`);
};

class Heavy {
constructor(char) {
this.large = new Array(100_000).fill(char);
}
}

function consume(char) {
const items = [];
for (let index = 0; index < 2500; index++) {
items.push(new Heavy(char));
}
return items;
}

main();

function main() {
console.log('-------------- FIRE and FORGET --------------');

console.log('start', memoryUsed());
consume('🗑️');
console.log('end', memoryUsed());
collectGarbage();

console.log('start', memoryUsed());
consume('🫰🏻');
console.log('end', memoryUsed());
collectGarbage();

console.log('start', memoryUsed());
consume('🚀');
console.log('end', memoryUsed());
collectGarbage();

console.log('-------------- KEEP the RESULT --------------');

console.log('start', memoryUsed());
const uno = consume('🙈');
console.log('end', memoryUsed());
collectGarbage();

console.log('start', memoryUsed());
const duo = consume('🌶️');
console.log('end', memoryUsed());
collectGarbage();

console.log('start', memoryUsed());
const tre = consume('🔥');
console.log('end', memoryUsed());
collectGarbage();
}

Browser Example

class Heavy {
constructor(char) {
this.large = new Array(100_000).fill(char);
}
}

function consume(char) {
const items = [];
for (let index = 0; index < 2500; index++) {
items.push(new Heavy(char));
}
return items;
}

const uno = consume('💯');
const duo = consume('🙏🏻');
const tre = consume('🌹');
const qad = consume('🙇🏻‍♂️');
const pen = consume('😢');
const six = consume('😭');

Freeing Memory

class Heavy {
constructor(char) {
this.large = new Array(100_000).fill(char);
}
}

function consume(char) {
const items = [];
for (let index = 0; index < 2500; index++) {
items.push(new Heavy(char));
}
return items;
}

let uno = consume('💯');
console.log('Example use:', uno[0].large[0]);
uno = null;

let duo = consume('🙏🏻');
console.log('Example use:', duo[0].large[0]);
duo = null;

let tre = consume('🌹');
console.log('Example use:', tre[0].large[0]);
tre = null;

let qad = consume('🙇🏻‍♂️');
console.log('Example use:', qad[0].large[0]);
qad = null;

let pen = consume('😢');
console.log('Example use:', pen[0].large[0]);
pen = null;

let six = consume('😭');
console.log('Example use:', six[0].large[0]);
six = null;

console.log('this is fine');
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

A critical fact worth knowing about JavaScript is its automatic memory management. Unlike low-level programming languages like CNC plus plus, we are not directly responsible for managing memory in JavaScript as it is done automatically by the built-in garbage collector browsers do not expose the underlying garbage collector. However, we can access it in a server environment like node js as an example. We can determine how much memory is being used by the JavaScript heap by using process memory usage. Additionally, we can even trigger a garbage collection manually if we wanted to. Let's just note the heap used before we trigger the garbage collection then

00:36

trigger a garbage collection using the node builtin global dot GC function, and then node the heap used afterwards. Using the before and after values, we can actually determine how much memory was freed up by that call to Global DOT GC. To demonstrate the garbage collector in action, we create a class heavy that creates a very large array consisting of a hundred thousand characters. Additionally, we create a function called consume that takes a character as an input and then creates a 2,500 array of heavies. Note that we create an array within consume and then return it.

01:12

So if we never store a reference to this array, when we call this function, then it should be available for garbage collection and the JavaScript GC should be able to free up that memory with this heavy infrastructure and utilities created. Let's just write on our code within a main function. First up, let's demonstrate the garbage collector in action by invoking the function, consume with different characters, but not storing that resulting array in any variable. We note on the memory that is currently being used by the process and consume a lot of memory for the trash emoji and then note on the memory being used

01:46

afterwards and then invoke the garbage collector. The garbage collector should be able to free up all the memory that the consume occupies and therefore we can do this as many times as we want and it should all work perfectly fine. Let's consume the memory with a few different emojis and every time we've made a consume call, we should see the memory consumption rise, and after the garbage collection, the memory consumption should decrease again. If however, we store the resulting array from consume into a variable, that would mean that the array is still within scope and the garbage collector will not be able to collect it.

02:19

And we should see our memory continue to rise after every single consume call where we are storing the results into different variables. As long as the variables Uno duo and tray are pointing to those arrays, the arrays will need to stay in memory and the garbage collector can't do anything. And now for the moment of truth that you have been waiting for, let's just execute this code and demonstrate it in action. Within our fire and forget version, we will do not store the result of consume. You can see that every single time the garbage collection call has been made, we have managed to free up a thousand mb. However,

02:52

when we keep the result into a variable, the memory consumption just keeps going up and up and the garbage collector Has not not been able to free any memory. Now, within JavaScript, we don't actually have to call the garbage collector ourselves. JavaScript would have jumped in and done that smartly depending upon how busy the code is and how much memory is available. But in node js, since it is a server environment, it does provide a hook to trigger it manually if you wanted to. If we keep allocating resources but do not free them up, eventually we will run out of memory and in the browser our tab will crash. Here we have the same utilities pasted into the browser console.

03:29

We have a class that creates a heavy character array and a consumed utility that creates a massive array consisting of heavy items. If he makes six different calls to consume, it's going to be perfectly fine because every single time a consume call is made, we discard the result, which means that that memory that has been allocated can be deallocate by the built-in garbage collector. However, if we start to store these results into different variables, that will mean that all of this memory will still hang around. The garbage collector can't do anything about it, and we will eventually run out of memory and the browser dev tools will actually

04:03

even pause pointing out that we are about to exhaust our resources. If we ignore this warning and push through with the code execution, we will eventually run out of memory and the browser tab has crashed. As you can see on the left hand side, of course, on a production site, the user is probably not going to have the dev tools open, so they will not get any warning. The website will just crash. The takeaway lesson is pretty simple. Whenever we are done with the value, we shouldn't keep a reference to it anymore. This will happen automatically if a variable goes out of scope. But if you still have the variable,

04:35

we can do simple things like assigning it to now. So we start again by pasting in the utilities for heavy and consume, and we will still make consume calls and store the results in different variables. This means that we can use the results, for example, to look at the first character, but after we are done with it, we will assign that variable to know and this will allow JavaScript to clear up that memory that was previously being occupied by that variable. So now if you run the code, even though the memory allocation might be high, we will not run out of memory because it'll be available for the garbage collected to collect as soon as the value is no longer referenced from our code.

05:13

Scap comes with an excellent garbage collector, and because of the browser wars, it's probably one of the best in the business, and you mostly don't need to think about memory management. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36