javascript var statement and performance

前端 未结 7 1564
后悔当初
后悔当初 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:01

    I will counter your question about performance with a few questions:

    1. Have you noticed an issue with performance?
    2. Have you determined that your var statement was the bottleneck?
    3. Have you tested each version?

    I'm going to assume the answer to all of these was no.

    None of the options should make any significant difference, although the only way to know for certain is to run them and test. JavaScript being an asynchronous client-side language means that you'd have to run a seriously enormous amount of code to have the var statements be a bottleneck of any sort.


    In the end, if you're deciding which version to use, I would recommend using a single var statement without assignment:

    function () {
        var a,
            b,
            c,
            foo,
            bar,
            fizz,
            buzz;
        a = 1;
        ...
        b = 3;
    }
    

    The reason for this is that this is essentially how the code will be executed due to variable hoisting. I can then move the initialize statement so where the variable is first used, such as in a for loop:

    function foo(arr) {
        var i,
            l;
        ...
        for (i = 0, l = arr.length; i < l; i++) {
            doStuff(arr[i]);
        }
        ...
    }
    

提交回复
热议问题