资讯专栏INFORMATION COLUMN

Memory Leak in JavaScript

LeviDing / 552人阅读

Memory Leak (內存泄漏)

Origin: https://aleen42.gitbooks.io/p...
Date: Sep, 10th, 2016

In the process of developing front-end application, like web application, "memory leak" means that a space created before cannot be used or collect any more until the browser is closed.

Though the browser has GC (Garbage Collection), but there is bug on this collection, which will lead to memory leak case.

Here we list some cases that will cause memory leak in JavaScript:

Event Listener

When a DOM has changed, if its event listener has not be removed, IE will not handle it for you and it causes memory leak.

In such kinds of cases, you can solve by remove the listner:

Or use event delegation(事件委託):

DOM or ActiveX Object Reference

In ECMAScript, reference between two DOM elements can be collected, if no other elements refer to them like:

var a = document.getElementById("xxx");
var b = document.getElementById("xx");

/** can still be collected */
a.reference = b;
b.reference = a;

However, in IE, if you loop to refer to any DOM or ActiveX Object, GC won"t collect and release these elements.

var a = document.getElementById("xxx");
a.reference = a;
Closure

Closures will sometimes cause memory leak by holding a variable.

function bindEvent() {
    var obj = document.getElementById("xxx");
    
    obj.onclick = function () {
        /** will keep holding obj even if it"s a empty function */
    };
}

For this situation, we can solve it by defining handling event outside the container:

function clickHandler() {
    /** handler for click event */
}

function bindEvent() {
    var obj = document.getElementById("xxx");
    
    obj.onclick = clickHandler;
}

Or directly release by deleting:

function bindEvent() {
    var obj = document.getElementById("xxx");
    
    obj.onclick = function () {
        /** empty function */
    };
    
    /** delete this reference */
    obj = null;
}
Delete loosely

Sometimes, if you delete an object loosely, it will result in memory leak:

var a = { p: { x: 1 } };
var b = a.p;

delete a.p;

console.log(b.x);   /** still output => 1 */

Therefore, when deleting an object, remember to delete recursively.

var a = { p: { x: 1 } };
var b = a.p;

function deleteObj(obj) {
    if (_.isObject(obj)) {
        delete obj;
        
        for (var i in obj) {
            deleteObj(i);
        }
    }
}
Boxing?

According to some documents, the following code will result in memory leak in IE, because IE will temporary create a String obj when accessing the property length, which will have a leak:

var s = "abc";

console.log(s.length);

Therefore, before we access any property of a value object, we are recommended to convert them before:

var s = "123";

console.log(new String(s).length);
Illegal DOM Operations?

Some illegal DOM operations will result in memory leak in IE, like we call appendChild of a DOM element, which is not in the DOM tree.

Pollution of the global namespace

Undefined variable will be defined in the global name-space, which is another memory leak:

function foo() {
    bar = "this is a hidden global variable";
}

Actually:

function foo() {
    window.bar = "this is a hidden global variable";
}

More worse:

function foo() {
    this.bar = "potential global";
}

foo();

Therefore, we can use the strict mode to limit our code:

/**
 * any acident global variable will thorw out an error
 * in the strict mode 
 */
"use strict";

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/90951.html

相关文章

  • Netty ByteBuf 谁负责谁释放

    摘要:转发自 转发自 http://netty.io/wiki/referenc... Since Netty version 4, the life cycle of certain objects are managed by their reference counts, so that Netty can return them (or their shared resources)...

    Lyux 评论0 收藏0
  • Memory Management and Circular References in Pytho

    摘要:一般情况下,的垃圾收集器会被用于检测上面这样的循环引用,并删除掉它们。你可以通过强制垃圾收集器运行,并检查列表里有什么来验证上述结论。 -- [since Python 3.4, circular references are handled much better](http://engineering.hearsaysocial.com/2013/06/16/circular-re...

    muddyway 评论0 收藏0
  • Node.js内存管理和V8垃圾回收机制

    摘要:垃圾回收内存管理实践先通过一个来看看在中进行垃圾回收的过程是怎样的内存泄漏识别在环境里提供了方法用来查看当前进程内存使用情况,单位为字节中保存的进程占用的内存部分,包括代码本身栈堆。 showImg(https://segmentfault.com/img/remote/1460000019894672?w=640&h=426);作者 | 五月君Node.js 技术栈 | https:...

    JowayYoung 评论0 收藏0
  • VueJS SSR 后端绘制内存泄漏的相关解决经验

    摘要:积少成多,最后造成内存泄漏。前端内存泄漏的影响,都是发生在客户机器上,而且基本上现代浏览器也会做好保护机制,一般自行刷新之后都会解决。但是,一旦后端绘制内存泄漏造成宕机之后,整个服务器都会受影响,危险性更大,搞不好年终奖就没了。 引言 Memory Leak 是最难排查调试的 Bug 种类之一,因为内存泄漏是个 undecidable problem,只有开发者才能明确一块内存是不是需...

    lifesimple 评论0 收藏0
  • 内存泄漏

    摘要:假如没有此时会进行优化把不会被任何闭包用到的变量从词法环境中去掉从而消除内存泄漏。良好的编码方式了解一下常见现象可以减少内存泄漏现象产生同时在由于失误产生泄漏时保持清醒的思路借助进行分析定位。 引言 内存泄漏一般是由于我们编码缺陷导致的,首先明确一下内存泄漏的定义,就是应用程序不需要,但是又不能返回给操作系统以供重新分配使用,导致可用内存越来越少的现象。下面总结一下在browser端内...

    jeffrey_up 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<