开发者

Does repeating variables cause a memory leak?

In reference to setting global and local variables, I've read about memory leaks and how to avoid them. I am still a little confused.

Let's just say that these examples occur deep within pages, where there are other global and local variables being used.

If I don't plan to reuse a variable, should I or should I not use var?

If I use var once within a function, do I need to use it again when I manipulate or modify the variable?

// EMAMPLE ONE
$("#AddBrandSave").click(function() {
    // DO THIS?
    Brand = $("#Brand").val();
    // OR DO THIS?
    var Brand = $("#Brand").val();
});

// EMAMPLE TWO
$("#AddBrandSave").click(function() {
    // DO THIS?
    Brand = $("#Brand").val();
    Brand = Brand.substring(7); 
    Brand = Brand.someMathFunction(); 
    // OR DO THIS?
    var Brand = $("#Brand").val();
    Brand = Brand.substring(7); 
    Brand = Brand.someMathFunction; 
    // OR DO THIS?
    var Brand = $("#Brand").val();
    var Brand = Brand.substring(7); 
    var Brand = Brand.someMathFunction()开发者_如何学Python; 
});


Understanding var

Javascript has exactly two levels of scope, global and function. When you use the var, the declaration of that variable is hoisted to the top of the scope it is in. For instance:

$("#AddBrandSave").click(function() {
    var Brand = $("#Brand").val();
    var Brand = Brand.substring(7); 
    var Brand = Brand.someMathFunction(); 
});

is interpreted as

$("#AddBrandSave").click(function() {
    var Brand;    
    Brand = $("#Brand").val();
    Brand = Brand.substring(7); 
    Brand = Brand.someMathFunction(); 
});

If you had not included var inside a function, "Brand" will be declared in the global scope, so

$("#AddBrandSave").click(function() {
    Brand = $("#Brand").val();
    Brand = Brand.substring(7); 
    Brand = Brand.someMathFunction(); 
});

is interpreted as:

var Brand; 
$("#AddBrandSave").click(function() { 
    Brand = $("#Brand").val();
    Brand = Brand.substring(7); 
    Brand = Brand.someMathFunction(); 
});
// The global variable Brand will only exist after #AddBrandSave is clicked
// or it will clobber the global variable Brand if it already existed

This is why it is suggested that you declare any variables you intend to use in a function with var at the top of that function, because that is what technically happens anyway so it makes it easier to understand.

Using var multiple times for the same variable could cause issues because it makes the interpreter work a little harder to check if that variable already exists - I don't know if it causes memory leaks, but why risk it?


The issue is actually one of variable correctness:

In JavaScript, if you don't use var in a function, the variable is assumed to be global and any actual global variables you might have under that name will be silently clobbered.

In most cases, you want to use var. Using it multiple times has no effect (and may even be an error). So you want the second approach in each of your examples.


When you create/use a variable, you should first decide if you want that variable to be a global variable (available everywhere in your program and it's value lasts forever) or a local variable (this variable only exists inside the current function scope and will be destroyed when the function scope completes).

In general, you want everything to be a local variable (because that is safer and better development practice) unless you absolutely have to make it global.

So, once you've figure out whether you want the variable to local or global, you can then decide how to use var.

For a local variable, you should declare it with var the first time it is defined in the function and then no other times in the function.

For a global variable, you should declare it with var outside the function and then use it without var inside the function. If you use it inside the function without declaring it with var anywhere, you will implicitly be declaring and using a global variable which is generally not a good practice as it's not easy for everyone to see what your intentions are and it's easy to accidentally make a mistake.

Some examples:

Declaring, then using a local variable named "i":

// here the variable i is declared separately as a local variable
function findIndex(array, val) {
    var i;
    for (i = 0; i < array.length; i++) {
        if (array[i] === val) {
            return(i);
        } 
    }
    return(-1);
}

// here the variable i is declared at first use as a local variable
function findIndex(array, val) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] === val) {
            return(i);
        } 
    }
    return(-1);
}

Explicit global variable "i":

// declaring i globally outside the scope of any function
var i;

// here the variable i is declared at first use as a local variable
function findIndex(array, val) {
    for (i = 0; i < array.length; i++) {
        if (array[i] === val) {
            return(i);
        } 
    }
    return(-1);
}

Implicit global variable "i" (bad idea):

// here the variable i is not declared at first use as a local variable and
// thus becomes a global variable (an implicit global declaration)
function findIndex(array, val) {
    for (i = 0; i < array.length; i++) {
        if (array[i] === val) {
            return(i);
        } 
    }
    return(-1);
}

When you use global variables, you must be aware that they can conflict with other code using global variables of the same name. There's a whole separate discussion about how to protect your global variables to make conflicts less likely. If you want to know more about that, search for "javascript namespacing". But, in general, you should never use a global variable unless you have to and when you do, you should either protect it in a namespace or give it very, very unique name that is unlikely to conflict with a name anyone else who contributes to your project (or any libraries you use) is using.

As for your question about memory leaks. Global or local variables are relevant to memory leaks in one particular way. Javascript and the browser DOM are garbage collected environments. That means that they free objects when there are longer any references to those objects in the DOM or in Javascript variables. So, if you remove an object from the DOM and don't have any references to that object in your code, it's memory will get freed.

If, on the other hand, you have a reference to that object in a global variable (global variables last forever), then even if you remove that object from the DOM or are done using that object in your javascript, as long as the global variable holds a reference to that object, its memory cannot be freed by the garbage collector. Local variables that are destroyed when the function finishes do not have this issue because their reference to things is usually automatically destroyed (there are a few exceptions in things called function closures) so you don't have to worry. So, as far as memory leaks, local variables are generally safer. Global variable references can be used when needed as long as the variable is cleared (setting it to null is a common way to clear it) when you you want an object to be capable of being freed.

Repeating a variable does not cause a memory leak.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜