javascript var statement and performance

前端 未结 7 1521
后悔当初
后悔当初 2021-01-18 10:29

Option1 : multiple var without assignment

function MyFunction() {

  var a = null;
  var b = null;
  ....
  var z = null;

  a = SomeValue;
         


        
7条回答
  •  臣服心动
    2021-01-18 11:00

    To understand the performance you should first understand hoisting. Let's take the following code:

    var x = 1;
    
    function bar(val) {
        var returnVal = val * 2;
    
        return returnVal;
    }
    
    function foo(val) {
        var returnVal = 10;
    
        returnVal *= bar(val);
    
        return returnVal;
    }
    
    var y = foo(x);
    
    console.log(y); // 20
    

    Hoisting basically means that the JavaScript interpreter will 'hoist' the variable declaration to the top of its scope. Making this example look more like this:

    var x, y;
    
    x = 1;
    
    function bar(val) {
        var returnVal;
    
        returnVal = val * 2;
    
        return returnVal;
    }
    
    function foo(val) {
        var returnVal;
    
        returnVal = 10;
        returnVal *= bar(val);
    
        return returnVal;
    }
    
    y = foo(x);
    
    console.log(y); // 20
    

    So, in your examples given, Option 2 and 3 will basically do the same thing. Since the interpreter will move those declarations to the top. At that point it's a decision of preference. A lot of people avoid doing something like var x, y, z; saying it's dangerous. I, personally, do it. In whatever scope I'm in I will declare all variables at the top, and then use them below. But either way works.

    Now, your first example is the least efficient. After hoisting it will look like this:

    function MyFunction() {
        var a, b, ... z;
    
        a = null;
        b = null;
        ...
        z = null;
    
        a = someValue;
        b = someValue2;
        ...
        z = someValueN;
    }
    

    It basically results in setting the variables twice.

提交回复
热议问题