02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Make them immutable

Reusing Instead of Creating

In this lesson, we focused on performance optimization through reusing arrays and objects rather than recreating them. This principle can significantly improve performance, especially in scenarios where arrays and objects are heavily utilized, such as in loops or high-refresh operations.


Key Concepts:

  1. The Cost of Creation

    • Object and array creation involves a constructor call, adding overhead.
    • Reusing existing structures avoids this cost, reducing application complexity.
  2. Resetting Arrays Efficiently

    • To Truncate an Array: Adjust its .length property (e.g., array.length = 20;).
    • To Reset an Array: Set its length to 0 (array.length = 0;).
  3. Reusing Objects

    • Instead of creating new objects inside loops, reset the properties of an existing object.
    • This is especially useful in high-frequency loops to save time and memory.
  4. Server-Side and Client-Side Benefits

    • Server-Side: Reduces resource overhead for frequently refreshed processes.
    • Client-Side: Enhances performance in interactive, high-refresh scenarios.

Code Example: Resetting an Array

// Resetting an existing array
let myArray = new Array(50); // Initially holds 50 items
for (let i = 0; i < myArray.length; i++) {
    myArray[i] = i;
}
console.log(myArray); // Array of 50 items

// Resize the array to 20 items
myArray.length = 20;
console.log(myArray); // Array now holds 20 items

Code Example: Reusing an Object in a Loop

// Avoid creating a new object for each iteration
let reusableObject = { value: 0 };

for (let i = 0; i < 10; i++) {
    reusableObject.value = i;
    console.log(reusableObject); // Resets and reuses the same object
}

Takeaway

By recycling arrays and objects, we reduce resource consumption and improve the efficiency of our applications. The lesson underscores the importance of these techniques in both server-side and client-side JavaScript development.

In 2024

The optimization techniques discussed in the video remain relevant in 2024. Reusing existing arrays and objects instead of creating new ones can lead to performance improvements in JavaScript applications. This approach reduces the overhead associated with object creation and garbage collection, which is particularly beneficial in performance-critical scenarios.

However, it's important to note that modern JavaScript engines have become more efficient in handling object creation and garbage collection. While reusing objects can still offer performance gains, the impact may be less pronounced than in earlier years. Developers should profile their applications to determine if object reuse provides a measurable benefit in their specific context.

In summary, reusing arrays and objects remains a valid optimization strategy in 2024, but its effectiveness depends on the application's specific requirements and the capabilities of the JavaScript engine in use.

Video Transcript

00:00We finally reached a highlight of this section,
00:02which is immutability.
00:04So how about we start by explaining what immutability is,
00:07by understanding what constants are.
00:10Why did we say constants?
00:11Constants are great because they can't change.
00:14And if they can't change it, one
00:16reduces our complexity of our code.
00:18Two, they also give us errors if we try to change something
00:21that's not supposed to change.
00:22Three, they improve our memory allocation performance
00:26inside of JavaScript.
00:28That is immutability. That's it. You know what it is? No.
00:30The idea of immutability takes that concept of concept
00:34and mo of constants and moves it into objects.
00:36So when you have multiple stores
00:38of information when they're stored
00:40inside an immutable object, the concept is is
00:43that the object itself that you're holding does not change.
00:46It cannot change. While if it goes a lot deeper than that,
00:51which we're gonna cover that in this se in this lecture,
00:52so let's just jump into understanding it.
00:54But that is the core concept of by making things not change,
00:58you're reducing their complexity,
01:00improving performance all over.
01:02And by creating that unchangeable state,
01:05you are saving a lot.
01:08Now we can take a look at the immutable JS library,
01:10which is a lot more than that.
01:11We're just gonna cover it in its really few steps
01:14of urge you to explore it deeply,
01:16because immutable js is gonna be a really powerful mechanism
01:20to make your code a lot more efficient.
01:23With that said, let's jump right into it
01:24and let's understand what immutability is
01:26through the immutable JS package.
01:30So far, while we were working,
01:32we talked about a few different layers.
01:34The first layer, we said whenever we're working,
01:36and if I just open something up that we've created recently,
01:40whenever we're creating variables, fine,
01:42we're creating variables.
01:44But generally speaking, we were talking about the fact that
01:48whenever we want, whenever we could, we'll use a constant.
01:51So throughout our navigation, we use constants
01:53because these constants are not changeable.
01:55And if they're not changeable, then only the amount
01:58of memory that needs to be allocated in memory is
02:01allocated for memory.
02:02Now, beyond that, we also said in the last few lectures
02:05that it's not a good idea to instantiate new objects.
02:08And whenever we can, we should avoid that, such
02:10as the situation where we could reset our rate and reuse it.
02:14Now, all this is good when we have a hard set of data,
02:18and that is all the data that we have and need.
02:21And this leads us to the next topic, which is,
02:24what do you do in these scenarios where you have something
02:26that you need to duplicate often,
02:28or you have something that you have to grow
02:30and you have something that is a list that is not predefined
02:34and to solve this problem
02:36because that is quite memory intensive.
02:38All this process of duplicating something
02:40or creating, for example,
02:42and I just wanna show you just just for the sake.
02:44For example, let's say I have a have another
02:45let, which is an object.
02:47And in this object we have, let's say a property
02:49that's, let's say a name.
02:51So that's a string. That's easy.
02:53Okay, but what if we have also here some sort of a object.
02:55So how about we'll have, uh, I don't know, like something
02:58And the something is an object
03:03of some type that has some sort of data.
03:05Now, for one, this object itself,
03:08because it's an object, could be updated and changed
03:11and modified, which means memory needs to be allocated.
03:13Further idea of updating it beyond that, even more over than
03:18that, if I want
03:19to create another reference without destroying my original
03:22item, and I wanted to create an O2,
03:25but I wanted O2 to have everything that's in there,
03:27but modify the name, I would have to duplicate
03:30or recreate this whole process again, which is
03:33processor intensive, memory intensive.
03:36'cause end of the day, I'm creating a new object
03:38and another new object.
03:39While in reality will, what I really wanted
03:41to do is just refer to that same, uh, object
03:44of oh something and not change it.
03:47The idea itself is instead of creating stuff
03:49that are mutable, which means that there are changeable is
03:52to create an object that cannot change anymore.
03:55But anytime I create a change,
03:57a new object construct would be created while it would
04:00leverage and use all the items that were there previously
04:03by doing that, and make sure
04:05that no one could come into changing something
04:07and turn that into something too,
04:08because if they change it into something too,
04:10then they would by return also change all the other
04:13somethings in the other items or approach and access
04:16and change something directly in the items.
04:18So to avoid a situation, what we really wanna do is we want
04:21to create a construct where I could duplicate an item,
04:24but nothing, and it could be changed
04:26and I could add new things,
04:27but when I add something new, I have to create a new item
04:30that would refer to all the other things
04:32that were created previously.
04:34Now, by doing that, what I'm actually doing is I'm cutting
04:36down the process of needing
04:38to create new things when new things
04:40don't need to be created.
04:41Now with that said, this goes a lot deeper than
04:44what I just said, and I just want to go ahead here
04:46and just comment this whole thing out
04:48because I want to showcase to you in, in, in, uh,
04:51how do you do this in JavaScript?
04:53Well, natively built in, we don't have that support,
04:56although we have libraries that enhance that.
04:58And Lee Bryan created a wonderful package,
05:03which is called Immutable.
05:04And check out the video, which is attached as one
05:06of the references to this title.
05:08Watch these 31 minutes.
05:09It's really gonna put in much more depth than we could in
05:13this title, all the different variations of immutability,
05:16and why is that such a big impact on performance?
05:20But just to get you running, I want to go ahead
05:22and show you how to create immutability.
05:24How do you create these contracts, which usually,
05:26basically you would want to use them all the time.
05:28In any scenario where you're storing data that you want that
05:31to be your model, you want that to be your content storage
05:33because anytime you make a change,
05:35you're not affecting the original.
05:37And if you need to duplicate things,
05:39these duplications will not actually
05:41create a lot of overhead.
05:42So let's go ahead and do that. And to be able
05:44to use the library, I'm gonna have to, first of all, uh,
05:47I'm gonna have to first of all stop my server
05:49because I have to go to NPM and install into save,
05:53and I want to install Mable, which is the library that
05:56We're gonna be working with.
05:58And let's go ahead and let it process that and install.
06:03And now that our library is running in install,
06:05let's go ahead and also start up our server again.
06:08And I'm gonna go back into my code and let's go ahead
06:11and start modifying and creating.
06:12So first of all, I'm gonna want to import the immutable,
06:15but I wanna import, I'm just gonna take one
06:17of the items there and you need to check that, that
06:19that video that is attached, which will really run through,
06:22um, everything in there, um, immutable.
06:26Okay? So I'm gonna show you just how to do it with a map,
06:29but the basic contract
06:30and the basic way this works, go, go and watch that video as well.
06:33And then start using immutable.
06:35Any place where you're working with data on a list
06:37that is not predefined, pre-configured, not like an array,
06:40which I know exactly in this
06:42situation, I only want 10 items.
06:43I don't need it. Don't have to use something immutable.
06:46I'll just define it in advance
06:47and say, Hey, this could only contain 10 items,
06:50but I'm gonna go ahead
06:51and show you basically how to, how to use immutable.
06:54So to to, to sample this, I'm just gonna go ahead
06:56and create a new constant, which I'm gonna call date,
06:59which is just gonna go ahead
07:00and just take a new date, object.
07:02Now I'm gonna create a few constants here.
07:04And the next one is I'm gonna be taking a map, a first map,
07:07and I'm just gonna call the map method,
07:09and I'm gonna send into it an object of data.
07:11For example, I have a, I have B as date,
07:15and let's say I have, um, C as just another number.
07:19Now that I've created this item, I'm,
07:22I can't change it anymore.
07:23I could only access its properties.
07:25Now, if I wanted to create any change, I would literally,
07:28what I do is I'm gonna call map two
07:29and I'm gonna create the, the change by calling map one
07:33and setting a new value, for example, into B.
07:36So let's say B will be equal a hundred now,
07:39and now I've created a new reference
07:42that will basically not change anything in B or C.
07:44It's gonna not recreate a new data object.
07:47It's actually going to use the date
07:48that already exists there
07:49because we can't change an item directly.
07:52So map one will still have
07:53that date while map two is gonna set something else
07:56inside while it's gonna reuse the A
07:58and C in, in our case with simple items.
08:01And it doesn't really make much, much sense,
08:02but if I had your a complex item,
08:04that would make it a lot more logical, such as other maps.
08:07Now, if I go ahead and I try to do a console log
08:11and I try to check if map one equals
08:15map two, and I go ahead and I run this application
08:20and I check it in my browser, we'll see that map one
08:23surely does not.
08:24Where is our falls here? Let's find it.
08:28Let me see if I trace that. Save that. Let's check.
08:33We should now have a trace here somewhere.
08:36Oh, we're having an arrow here.
08:38Con that's not defined console save.
08:44And we should now see our false because they're not equal.
08:48But if I go ahead and create another item,
08:51and in this new item
08:52that I'm creating, I'm gonna go ahead and create
08:55Map three, for example.
08:56And map three is gonna tape map two and set B again.
08:59But this time around, I'm gonna put in the same item in
09:02there, the same value inside there.
09:04What actually is gonna happen, it's gonna revert back,
09:06it's gonna revert back
09:08and create the exact same reference as we had before.
09:10So if I check if map one equals map three,
09:14then actually map one is map three,
09:16and it's explicitly map three.
09:18So if I go ahead and check this again, I'll see
09:20that now our map three is exactly true and it's equal.
09:23Now this is a very simplistic explanation of this,
09:26but behind the hood, and if you take a deeper look into the
09:30library, it's open to that video that I, uh, I shared
09:32with you In that video,
09:33you'll find a few really fascinating
09:35charts that really showcase.
09:37If I just like, uh, jump in time here somewhere, uh,
09:41you'll, you'll, you'll find it.
09:42But really watch that video in a hole.
09:44It has wonderful charts that really explain the logic behind
09:47of these immu abilities
09:49and how these immu imu immu abilities work
09:53and really walks you through why it's so much more efficient
09:56and why in the scenario, for example,
09:57if I'm setting something new here
09:59and all these stuff didn't change,
10:01it's not gonna create all these new things,
10:02it's just gonna keep a reference
10:04to these old things while it creates a new
10:06reference to the new item.
10:08So basically what's what's happening is it's creating this
10:10spider web that is really, really good for performance.
10:13That's the really basic of the
10:15chart that I wanted you to see.
10:16But overall, check out this video.
10:18It's an incredibly powerful video
10:20that completely changed the way you work with data
10:22and JavaScript in general.
10:24So with that said, that's all we're really gonna talk about
10:26in this lecture about IMU ability,
10:29but is incredibly, incredibly something
10:31that could make a major impact on your performance if you're
10:35building and working with data,
10:36especially if you're duplicating items,
10:38especially if there's complex data involved
10:40that is not pre-configured.
10:41Because once you're setting it all as constants
10:44that are not changing, then it automatically,
10:46you're using less memory
10:47because you're not working with an array, for example,
10:50that has an endless amount.
10:51It could continue growing. So for that, it needs
10:53to allocate memory room
10:55or if it's an object, which is I, which is mutable,
10:58which means that it's gonna change.
10:59So if it's gonna change, then there's needs for more memory
11:02for to be able to deal with that as well.
11:03So all these stuff will really cut down very
11:06dramatically on your performance.
11:07You're really encouraged to check that video out
11:10and start incorporating this style of writing variables
11:13and working with collections in JavaScript.
11:18In this lecture, we explored the mutable JS package
11:20and I hope that you're incredibly excited just as much
11:23as I was to create this lecture.
11:26With that said, we're almost done with this section.
11:28We have another lecture that we want to cover
11:30before we wrap up this section,
11:32and that is going to be about how to work
11:36with react events or how to work with with events in React
11:39and not create memory leaks.
11:41Because if you're working with events,
11:43there is a good probability
11:44that you are creating memory leaks if you're not doing it
11:47the right way.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!