loading...
Cover image for Learn Data Structure and Algorithm in JavaScript | Part 07

Learn Data Structure and Algorithm in JavaScript | Part 07

edisonpebojots profile image Edison Pebojot(πŸ‘¨β€πŸ’») Updated on ・9 min read


Prerequisite (βœ‹πŸ˜)

If you're reading this article right now, please considered to read our Part 01: Big-O Notation, Part 02: JavaScript Unique Part, Part 03: JavaScript Numbers, Part 04: JavaScript Strings, Part 05: JavaScript Array and Part 06: JavaScript Object

Part Table of Contents Description
01 Big-O Notation By the end of this chapter, you will understand how to analyze an implementation of an algorithm with respect to both time (execution time) and space (memory consumed).
02 JavaScript Unique Parts Big-O is important for analyzing and comparing the efficiencies of algorithms. The analysis of Big-O starts by looking at the code, and, applying the rules, applying the rules is because to simplify the Big-O notation linear or quadratic rule is not enough.
03 JavaScript Numbers This part 3 will focus on JavaScript number operations, number representation, Number objects, common number algorithms, and random number generation.
04 JavaScript Strings This part 4 will focus on strings, JavaScript String object, and the String object’s built-in functions. You will learn how to access, compare, decompose, and search strings for commonly used real-life purposes. In addition, the chapter will explore string encoding, decoding, encryption, and decryption.
05 JavaScript Arrays As a JavaScript developer, you will use the array often; it is the most commonly used data structure. Arrays in JavaScript come with a lot of built-in methods. By the end of this part, you will understand arrays and choose the right method
06 JavaScript Object This part will focus on what JavaScript objects are, how they are declared, and how their properties can be changed. In addition, this part will cover how JavaScript classes are implemented using prototypal inheritance. Also this part will be short.
07 JavaScript Memory Management A variable takes up some memory. In C, the programmer allocate and deallocate memory manually. In contrast, modern JavaScript engines have garbage collectors that delete unused variables. However, there are pitfalls(unexpected) that developers can fall into(❗) This part will show these unexpected and present techniques to help the garbage collector minimize the memory problems.
08 Recursion This part 8 introduces the concept of recursion and recursive algorithms(Remember they are different, we will discuss them later(πŸ˜‰)). We will also discuss the definition of recursion and fundamental rules for recursive algorithms.
09 Sets This part focuses on the concepts of sets from both a mathematical definition and on the implementation. Also, Common set operations, as well as their implementations, are covered in great detail (πŸ’‘).
10 Searching and Sorting This part 10 focuses on searching and sorting for arrays. By the end of this part 10, you will understand how to use sorting and searching algorithms for arrays. Also, this article is a bit complicated for beginners, so as much as possible the visual aids is your friend (πŸ‘€). (πŸ˜ƒ)
11 Hash Tables A hash table is a fixed-sized data structure in which the size is defined at the start. This part 11 explains how hash tables work, and the method of generating a unique key. By the end of this part 11, you will understand various hashing techniques and know how to implement a hash table. (πŸ˜ƒ)
12 Stacks and Queues This part 12 covers stacks and queues(pronounce as kyooz (πŸ”ˆ)) not (kwewe) okay? hehehe (πŸ˜…); both are data structures used in the implementation of complex data structures. You'll learn what the stacks and queues are, how they're used, when they're used, and how to implement them (πŸ˜ƒ) Let's go! (πŸ”₯πŸ”₯πŸ”₯)

Part 07: JavaScript Memory Management(😱 πŸ”₯ πŸ’Ύ)

Alt Text

A variable takes up some memory. In C, the programmer allocate and deallocate memory manually. In contrast, modern JavaScript engines have garbage collectors that delete unused variables. However, there are pitfalls(unexpected) that developers can fall into(❗) This part will show these unexpected and present techniques to help the garbage collector minimize the memory problems. (πŸ˜‰)

Memory Leaks (πŸ’ΎπŸ’Ύ)

Alt text

A memory leak is a failure in a program causing impaired
performance
and even failure. Memory leaks can happen when garbage collectors (See on Wikipedia) do not free memory properly. Follow the key principles in this part to avoid memory leaks:

Reference to an Object (πŸ“¦βž‘οΈπŸ“¦)

In this example, say the memory() function returns 5KB of data:

Example:


var foo = {
    bar1: memory(), // 5kb
    bar2: memory() // 5kb
}

function clickEvent(){
    return foo.bar1[0]
}

clickEvent()

Execution:

function memory() { return ['I am 10 kilobytes'] } var foo = { bar1: memory(), // 5kb bar2: memory() // 5kb } function clickEvent(){ return foo.bar1[0] } clickEvent()

You might expect the clickEvent() function to use 5KB of memory since it is only referencing bar1 from the foo object (😏). The truth is (😌), it is using 10KB of memory since it has to load the whole foo object into the function’s scope to access the bar1 property. (πŸ˜ƒ)

Leaking DOM (πŸ’¦πŸ‘ŒπŸ‘ˆ)

If a variable pointing to a DOM element declared outside of an event callback, then it is in memory leaks if the element is deleted. In this example, there are two elements selected by document.getElementByID:

Example:


<div id="one">One</div>
<div id="two">Two</div>

The following code in the Glitch sample below demonstrates the memory leak. When one is clicked, it removes two:

Note(πŸ“): When one is clicked again, it still tries to reference the removed element, you can see it when the [object HTMLDivElement] still show multiple times. Click the view app and click one. Also, don't forget to see the script.js and index.html to see the idea how it works. (πŸ‘)

The event listener will cause the two to disappear from the web. However, the reference to it will remain in event callback. This is a memory leak and should be avoided. (⚠️)

This can easily be fixed so that it won’t cause a memory leak, as shown here:

Example:


var one = document.getElementById("one");

one.addEventListener('click', function () {
    var two = document.getElementById("two");
    two.remove();
});

Test it here:

Note(πŸ“): If you fixed it, you can see the [object HTMLDivElement] is not showing multiple times, but only once, this is because we fixed the memory leak

Another way to address this is by unregistering the click handler once it has been used, as shown here:


var one = document.getElementById("one");
function callBackExample() {
    var two = document.getElementById("two");
    two.remove();
    one.removeEventListener("click", callBackExample);
}
one.addEventListener("click", callBackExample);


Test it here:

Note(πŸ“): If you fixed it, you can also see the [object HTMLDivElement] is not showing multiple times, but only once, this is because we fixed the memory leak by unregistering the click handler

Global window Object (πŸŒπŸ”πŸ“¦)

If an object is on the global window object, it is in memory(meaning it is store in a memory). Any objects declared as a property of window will not be cleared. Remember that any global variable declared will be set as a property of the window object. In this example, there are one global variables declared:

Example:


var a = "apples"; //global variable

console.log(window.a); // prints "apples"

Execution:

Note(πŸ“): Click the view app and see the apples. Also, don't forget to see the script.js to see the idea how it works. (πŸ‘)

Note(πŸ“): It is good to avoid global variables whenever possible. This will help save memory. (πŸ˜ƒ)

Limiting Object References (πŸ“πŸ“¦βž‘οΈ)

An object is cleared when all references are cleared. Always remember to pull the property of an object instead of the entire object. This is because the object’s memory footprint can be very
large. If only one of the object’s properties is needed, you should avoid using the entire object as a parameter.

For example, do not do this(⚠️):

Example:


var test = {
    prop1: 'test'
}

function printProp1(test) {
    return test.prop1;
}

printProp1(test); // Prints 'test'

Execution:

var test = { prop1: 'test' } function printProp1(test) { return test.prop1; } printProp1(test); // Prints 'test'

Instead, do this(pass the property like this)(🌻):

Example:


var test = {
    prop1: 'test'
}

function printProp1(prop1) {
    return prop1;
}

printProp1(test.prop1); // Prints 'test'

Execution:

var test = { prop1: 'test' } function printProp1(prop1) { return prop1; } printProp1(test.prop1); // Prints 'test'

The delete Operator (❌❌❌)

Always remember that the delete operator can be used to delete an unwanted object property (though it does not work on non-objects). Here's an example:

Example:


var test = {
    prop1: 'test'
}

console.log(test.prop1); // Prints 'test'

delete test.prop1;

console.log(test.prop1); // Prints 'undefined'

Execution:

var test = { prop1: 'test' } console.log(test.prop1); // Prints 'test' delete test.prop1; console.log(test.prop1); // Prints 'undefined'

Summary (πŸ“š)

Alt text

Although memory in JavaScript is not allocated by the programmer, there are still ways to mitigate memory leaks. If the object is in reference, it is in memory(meaning it is store in the memory). Similarly, DOM elements should not be referenced once deleted. In many cases, it is more applicable to pass a property of the object rather than the object itself. Also, be extremely mindful when declaring a global variable.

Challenge (😀πŸ”₯πŸ‘Š)

Alt text

In this part, challenges are about identifying memory inefficiencies and optimizing a given piece of code. Have some time to solve this riddle while waiting for part 8. Just make sure to share your solution in the comment: (πŸ˜ƒ)


ANALYZING AND OPTIMIZING A PROPERTY CALL

Problem: An excessive amount of memory is used in printProperty because the entire object is brought into the printProperty function. To fix this, only the property being printed should be brought in as a parameter of the function. Analyze and optimize the call for printProperty:

Sample:


function someLargeArray() {
    return new Array(1000000);
}
var exampleObject = {
    'prop1': someLargeArray(),
    'prop2': someLargeArray()
}
function printProperty(obj) {
    console.log(obj['prop1']);
}
printProperty(exampleObject);

Answer: (Remember to put your answer in the comment)


ANALYZING AND OPTIMIZING SCOPE

Problem: Global variables are used where not necessary. Albeit(although.) small, the global variables RED, GREEN, and BLUE bloat the global scope and should be moved inside the redGreenBlueCount function. Analyze and optimize the global scope for the following code block:

Sample:


var RED = 0,
    GREEN = 1,
    BLUE = 2;
function redGreenBlueCount(arr) {
    var counter = new Array(3).fill(0);
    for (var i = 0; i < arr.length; i++) {
        var curr = arr[i];
        if (curr == RED) {
            counter[RED]++;
        } else if (curr == GREEN) {
            counter[GREEN]++;
        } else if (curr == BLUE) {
            counter[BLUE]++;
        }

    }
    return counter;
}
redGreenBlueCount([0, 1, 1, 1, 2, 2, 2]); // [1, 3, 3]

Answer: (Remember to put your answer in the comment)


ANALYZING AND REPAIRING MEMORY ISSUES

Problem: This is the leaking DOM issue discussed earlier in the part. When elements are removed, they are still referenced by the callback function. To address this, put the one and two variables into a callback’s scope and remove the event listener after. Analyze and fix memory issues for the following code:

Sample HTML:

<button id="one">Button 1</button>
<button id="two">Button 2</button>

Sample JavaScript:


var one = document.querySelector("#one");
var two = document.querySelector("#two");
function callBackExample() {
    one.removeEventListener("", callBackExample);
}
one.addEventListener('hover', function () {
    two.remove();
    console.log(two); // will print the html even after deletion
});
two.addEventListener('hover', function () {
    one.remove();
    console.log(one); // will print the html even after deletion
});

Note(πŸ“): Make sure by answering is to use glitch

Answer: (Remember to put your answer in the comment)


Up NextπŸ‘‰ Part 08: Recursion (πŸ”₯πŸ”₯) (July 16-17, 2020)


Alt text

Discussion

markdown guide