首页 > 编程语言 >Understanding JavaScript Garbage Collection: Dive into Reference Counting and Mark-and-Sweep Algorit

Understanding JavaScript Garbage Collection: Dive into Reference Counting and Mark-and-Sweep Algorit

时间:2023-06-19 14:24:20浏览次数:43  
标签:object garbage reference into JavaScript Sweep Mark Garbage Reference

JavaScript, the programming language of the web, is often praised for its ability to handle memory management automatically. The JavaScript engine's garbage collector plays a pivotal role in this process. Today, we'll take a deep dive into two main garbage collection algorithms: Reference Counting and Mark-and-Sweep.

 

Reference Counting: An Early Approach to Garbage Collection

One of the earliest garbage collection strategies employed by JavaScript is reference counting. This algorithm is straightforward: an object's "reference count" increases each time a reference is made to it and decreases when a reference is removed.

Let's consider a simple example:

let objA = {};
let objB = objA;  // The reference count for objA is now 2
objB = null;      // The reference count for objA decreases to 1

When an object's reference count drops to zero (indicating that no other objects are referring to it), it becomes eligible for garbage collection. In other words, it's considered "garbage" and is swept away, freeing up memory.

However, reference counting isn't without its problems. The most significant issue is handling circular references. If object A refers to B, B refers to C, and C refers back to A, we have a circular reference. Even if these objects are no longer accessible from the root, their reference count never reaches zero, resulting in a memory leak.

 

The Mark-and-Sweep Algorithm: Handling Circular References

To address the shortcomings of reference counting, modern JavaScript engines, like V8 and SpiderMonkey, implement the Mark-and-Sweep algorithm. Unlike reference counting, this algorithm can effectively deal with circular references.

The Mark-and-Sweep algorithm works in two phases:

Mark Phase: The garbage collector starts from the roots (i.e., the global object in browsers and the global and process objects in Node.js). It marks these objects and any objects they reference, and so on. At the end of this phase, all reachable objects are marked.

Sweep Phase: The garbage collector then deallocates any unmarked objects, effectively freeing up memory.

Here's a simple demonstration of the Mark-and-Sweep algorithm:

let a = { name: 'object a' };  // a is reachable from the root
let b = { name: 'object b' };  // b is reachable from the root
a.other = b;  // a and b are interconnected
b = null;     // b is now null, but the actual object { name: 'object b' } is still reachable through a
a = null;     // a is now null, and neither object is reachable from the root anymore

In the last line, after we set a to null, both objects become unreachable and will be swept away by the garbage collector during the next cycle.

However, the Mark-and-Sweep algorithm has its drawbacks. Marking and sweeping all objects can cause application pauses, which might lead to a less responsive user interface. To mitigate this, modern JavaScript engines use several optimization strategies such as incremental and idle-time garbage collection.

 

In Conclusion

Understanding the basics of JavaScript's garbage collection, particularly the Reference Counting and Mark-and-Sweep algorithms, can be instrumental in writing efficient, performance-optimized code. It provides valuable insight into how JavaScript handles memory allocation and deallocation under the hood, contributing to the overall smooth operation of your web applications.

While JavaScript does most of the heavy lifting when it comes to memory management, it's essential to avoid pitfalls such as circular references and unnecessary global variables, which can cause memory leaks and hamper performance. The key takeaway is to be mindful of your references. When an object is no longer needed, ensure it isn't being referenced so that the garbage collector can do its job effectively.

Remember, although JavaScript engines handle garbage collection automatically, as developers, we can write code that makes the process as smooth and efficient as possible. When we understand what happens behind the scenes, we can better optimize our code, improve application performance, and provide a better user experience.

That's it for today's post on JavaScript's garbage collection. Happy coding, and may your applications always be free of memory leaks!

 

标签:object,garbage,reference,into,JavaScript,Sweep,Mark,Garbage,Reference
From: https://www.cnblogs.com/Answer1215/p/17491033.html

相关文章

  • vue3+vite+web3.js报错ReferenceError: process is not defined
    在vite最新版本中使用web3会报错只需要在vite.config.ts添加如下代码即可解决报错import{fileURLToPath,URL}from'node:url'import{defineConfig}from'vite'importvuefrom'@vitejs/plugin-vue'//引入import{resolve}from'path'export......
  • Cannot Reference “XxxClass.xxxmember” Before Supertype Constructor Has Been Ca
    在调用超类型构造函数之前无法引用“XxxClass.xxx”-----在一个类的构造器方法还未执行的时候,我们无法使用这个类的成员属性或成员方法。百度翻译:在调用超类型构造函数之前无法引用“XxxClass.xxx”-----我的理解:在一个类的构造器方法还未执行的时候,我们......
  • Weak References in .NET
    今天看到一个老外,用C#代码讲WeakReferences的用法不过我发现它的例子应该是用毛病的,在它的例子中weakRef应该没有逃开作用域,不能被正确回收,所以例子的结果也是不准的末尾给出了我对其修改后的例子,给出了两种作用域的对比DecidingWhentoUseWeakReferencesin.NET ......
  • Cannot Reference “XxxClass.xxx” Before Supertype Constructor Has Been Called
    百度翻译:在调用超类型构造函数之前无法引用“XxxClass.xxx”-----我的理解:一个类的构造器方法还未执行的时候,我们无法使用类的成员属性或成员方法。 下面是此错误的示例代码publicclassMyExceptionextendsRuntimeException{privateinterrorCode=0;......
  • C++ 模板类编译过程中出现“undefined reference to”问题
    问题描述C++在使用模板(template)类的时候,如果将类的成员函数的声明和实现分别放在.h头文件和.cpp源文件中,编译时会报错undefinedreferencexxx,找不到对应成员函数。起因.h文件中类的声明为://线程池,定义成模板类,为了代码的复用template<typenameT>classThreadPool{......
  • 关于VS2022使用EF生成实体模型报错的问题:运行转换:System.NullReferenceException:对象
    起因:之前版本vs2022生成EF模型一直没有问题,在更新了最新的vs2022之后,版本号17.6+,出现此问题:运行转换:System.NullReferenceException:对象引用未设置为对象的示例。在Microsoft.VisualStudio.TextTemplatingD21DB4521EFD493FAE41A9CE9DA80C875F3084552987498BD518713BDE91D14A......
  • 外汇天眼:FINTOCH又传诈骗案! 新竹妇人入金149万领不回
    最近网络爆出多起资金盘诈骗案,除了引发社会大众关注的「imB诈骗案」外,上个月外汇天眼也发布了「投资人注意!FINTOCH“分投趣”遭爆为假借贷资金盘! 」这篇文章,呼吁所有用户小心这个平台,没想到前几天又出现新的受害者。从外汇天眼之前的报道可以知道,FINTOCH借贷理财收益每天报酬率有......
  • US firm's official entry into segment to motivate more Chinese peers to join in
    AppleInc'saugmentedrealityheadsetwillhelpacceleratethedevelopmentoftheARindustrialchaininChina,andpushtheproductnotonlyforentertainmentbutalsoasaproductivetoolforwork,expertssaid.ThecommentscameaftertheUScompa......
  • mysql select into outfile 语法 乱码问题
    一个常见的问题,mysql导出csv格式的语法,已经乱码问题:由于数据库一般默认的是UTF-8格式的字符集,而execl默认的是gbk格式的字符集,这里有两种方法解决乱码:方法一:先转出.txt格式的文件,然后选择用excel打开时,提示选择哪种编码打开,选择gbk即可select*frommobile_order_regionwhere......
  • 5分钟部署 Apinto 开源网关
     Apinto 的开源网关符合我的需求,下面我将演示如何部署这样一个开源网关。Apinto功能架构图开始部署部署资源设备推荐配置设备数量部署对象4核8G,250G磁盘空间,2.5GHz1控制台程序、Mysql数据库、Redis数据库4核8G,250G磁盘空间,2.5GHz2网关节点部署架构控制台程序、mysql数据库、redis......