简体   繁体   English

避免使用var可以减少内存使用吗?

[英]Can memory usage be reduced by avoiding var?

Let's say I have a class MyClass with a function method() that is going to be called a lot . 假设我有一个带有函数method() MyClass类,该类将被大量调用。 Which of these implementations is going to be more efficient? 这些实施中的哪一个将更有效?

function MyClass() {
    this.method = function () {
        var number = 10;
        var boolean = true;
        var string = "string";

        // do something
    };
}

function MyClass() {
    this.data = {};
    this.method = function () {
        this.data.number = 10;
        this.data.boolean = true;
        this.data.string = "string";

        // do something
    };
}

The first implementation creates new variables which will be eligible for garbage collection after the execution of the function since there's no reference to them, which is great. 第一个实现创建新变量,该新变量在执行函数后将有资格进行垃圾回收,因为没有引用它们,这很好。 However, if I call the function 3 times, there is memory allocated for a total of 3 numbers, 3 booleans and 3 strings. 但是,如果我调用该函数3次,则会为总共3个数字,3个布尔值和3个字符串分配内存。

The second implementation doesn't create new variables, it simply overwrites the values of the previous call of the function instead. 第二种实现方法不会创建新变量,而只是覆盖函数上一次调用的值。 Does this mean that after 3 invocations of the function, the memory allocated is just for 1 number, boolean and string, instead of 3? 这是否意味着在调用该函数3次之后,分配的内存仅用于1个数字,布尔值和字符串,而不是3个? Is there really 3 times less memory consumed? 真的消耗的内存少三倍吗?

function MyClass() {
    this.method = function () {
        var number = 10;
        var boolean = true;
        var string = "string";

        // do something
    };
}

First approach is better as the variables are method scope and will be collected by GC once method execution is complete. 第一种方法更好,因为变量属于方法范围,方法执行完成后将由GC收集。 But keep in mind if you have to keep these values as class members then this method will not work. 但是请记住,如果必须将这些值保留为类成员,则此方法将不起作用。

In second approach you are attaching these properties with class reference. 在第二种方法中,您将这些属性与类引用一起附加。 So GC will not collect it until the class instance is referenced with some scope. 因此,在类实例被某个范围引用之前,GC不会收集它。

Your second approach looks very logical and accessible. 您的第二种方法看起来非常合逻辑且易于访问。 I believe code is poetic and it tells a lot about persistence. 我相信代码是富有诗意的,它讲述了很多有关持久性的知识。

function MyClass() {
    this.data = {};
    this.method = function () {
        this.data.number = 10;
        this.data.boolean = true;
        this.data.string = "string";

        // do something
    };
}

the above code looks efficient and well structured than creating more var every single time your class is called. 与每次调用您的类每次创建更多的var相比,以上代码看起来高效且结构良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM