未加星标

Eradicating Memory Leaks in Javascript

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

If you are wondering why your javascript app is suffering from severe slowdowns, poor performance, high latency, or frequent crashes, and all your painstaking attempts to figure out the problem were to no avail, there is a pretty good chance that your code is plagued by ‘Memory Leaks.’ Memory leaks are fairly common as memory management is often neglected by developers due to the misconceptions about automatic memory allocation and release in modern high-level programming languages like JavaScript . Failure to deal with memory leaks can wreak havoc on your app’s performance and can render it unusable. The Internet is flooded with never-ending complex jargon which is often difficult to wrap your head around. So in this article, we will take a comprehensive approach to understand what memory leaks are, their causes, and how to spot and diagnose them easily using Chrome Developer Tools.

What Are Memory Leaks?

A memory leak can be defined as a piece of memory that is no longer being used or required by an application but for some reason is not returned back to the OS and is still being needlessly occupied. Creating objects and variables in your code consumes memory. JavaScript is smart enough to figure out when you won’t need the variable anymore and will clear it out to save memory. A memory leak occurs when you may no longer need an object but the JS runtime still thinks you do. Also, remember that memory leaks are not caused by invalid code but,rather, a logical flaw in your code. It leads to the diminished performance of your application by reducing the amount of memory available for it to perform tasks and could eventually lead to crashes or freezes.

Before diving deeper into memory leaks, it is crucial to have a sound understanding of memory cycles, memory management systems, and garbage collector algorithms.

What Is a Memory Cycle?

A piece of ‘memory’ consists of a series of flip-flops, which is a 2-state (0 and 1) circuit composed of 4 to 6 transistors. Once the flip-flop stores a bit, it will continue to retain it until it is rewritten with the opposite bit. So memory is an array of reprogrammable bits. Each and every single piece of data being used in a program is stored in the memory. A memory cycle is the complete sequence of events for a unit of memory to go from an idle/free state through a usage (read or write) phase, and back to the idle state.

A memory lifecycle can be broadly broken down to 3 major steps:


Eradicating Memory Leaks in Javascript
Memory Allocation: memory is allocated by the OS to the program during execution as needed. In low-level languages like C and C++, this step is handled by the programmer, but in high-level languages like JavaScript, this is done on its own by the automatic memory management system. Here's an exampleof memory allocation in JavaScript:
Eradicating Memory Leaks in Javascript
Memory Usage: The program performs read and write functions on the allocated memory. This can be reading or writing the value of a variable, an object, or even passing an argument to a function. Memory Release: When the task is finished and allocated memory is no longer needed, it is released and made free for new allocations.

The third step of the memory cycle is where the complications lie. The most difficult challenge here is to determine when the allocated memory is not needed any longer and should be freed. This is where memory management systems and their garbage collector algorithms come to the rescue.

Memory Management Systems: Manual vs. Automatic

Different programming languages use different approaches depending on their complexity to deal with memory management.

Low-level languages like Pascal, C, and C++ have manual memory management systems where the programmer must manually/explicitly allocate memory when needed and then free up the memory after it has been used by the program. For example, C uses malloc() a nd calloc() to reserve memory, realloc() to move a reserved block of memory to another allocation, and free() to release memory back to the system. High-level programming languages like JavaScript and VB have an automated system that allocates memory each time you create an entity like an object, an array, a string, or a DOM element, and automatically frees it up when they are not used anymore, by a process called garbage collection. Memory leaks happen when your program is still consuming memory, which ideally should be released after the given task was completed. If for some reason, the garbage collector fails to serve its purpose and the program refuses to release the memory, the memory will keep on being consumed without any need for it to happen. Garbage Collectors

Garbage collectors execute the process of finding memory which is no longer in use by the program and releasing it back to the OS for future reallocation. To find the memory which is no longer being used, garbage collectors rely on algorithms. Though the garbage collection method is highly effective, it is still possible for memory leaks to occur in JavaScript. The main cause for such leaks is very often an ‘unwanted reference.’ The primary reason for this is the fact that garbage collection process is based on estimations or conjectures, as the complex problem of whether some memory needs to be freed cannot be determined by an algorithm correctly at every instance.

Before moving further, let’s take a look at the two most widely used garbage collection algorithms.

Like we discussed earlier, any garbage collection algorithm must perform two basic functions. It must be able to detect all the memory that is no longer in use and it must free/deallocate the space used by the garbage objects and make it available again for reallocation in the future if needed.

The two most popular algorithms are:

Reference count Mark and Sweep Reference Count Algorithm

This algorithm relies on the notion of a ‘reference.’ It is based on counting the number of references to an object from other objects. Each time an object is created or a reference to the object is assigned, it’s reference count is increased. In JavaScript, every object has an implicit reference to its prototype and explicit reference to its property values. Reference count algorithms are the most basic garbage collector algorithms. They reduce the definition of “an object is not needed anymore” to “an object has no other objects referencing it.” An object is considered garbage collectible and deemed to be no longer in use if there are zero references pointing to it.


Eradicating Memory Leaks in Javascript
Drawbacks of a Reference Count Algorithm

There is, however, a big limitation to reference counting algorithms in the case of cycles.

A cycle is an instance where two objects are created by referencing one another. Since both the objects have a reference count of at least one (referenced at least once by each other), the garbage collector algorithm does not collect them even after they are no longer in use.


Eradicating Memory Leaks in Javascript
Mark-and-Sweep Algorithms

Unlike the reference count algorithm, mark-and-sweep reduces the definition of “an object is not needed anymore” to “an object is unreachable” rather than “not referenced.” In JavaScript, the global object is called ‘root.’

Garbage collectors will first find all the root objects and will map all references to these global objects and re

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Eradicating Memory Leaks in Javascript
本站链接:https://www.codesec.net/view/628312.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(139)