6

Option1 : multiple var without assignment

function MyFunction() {

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

  a = SomeValue;
  b = SomeValue2;
  ....
}

Option 2: one var statement, no assignment

function MyFunction() {

  var a, b ..., z;

  a = SomeValue;
  b = SomeValue2;
  ....
}

Option 3: multiple var statements with assignment

function MyFunction() {

  var a = SomeValue;
  var b = SomeValue2;
  ....
  var z = SomeValue26;
}

Is there any performance benefit of using a particular option? Is it true for both primitive type assignments AND object reference assignments?

Thanks for your input.

gdoron
  • 147,333
  • 58
  • 291
  • 367
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 2
    i dunno about performance differences but stylistically i would go with option 3. – c0deNinja Mar 12 '12 at 18:28
  • 1
    There are so many thing that can impact your performance further, that you shouldn't bother with this... Just do whatever you find easier to read, as this won't impact performance. Plus, it may vary depending on what JS engine you are using. – Ortiga Mar 12 '12 at 18:30
  • 2
    Note that option 1 is not really what you're calling it. There are actually *two* assignments: once when you declare the variable *and assign `null` to it*, then again when you assign `SomeValue`. – josh3736 Mar 12 '12 at 18:33
  • 1
    Assigning a value at declaration is significantly faster (see [this jsPerf](http://jsperf.com/var-type-comparison)).However whether you use multiple var statements or not, doesn't really matter. – Chad Mar 12 '12 at 18:33

7 Answers7

17

"premature optimization is the root of all evil"

I don't think there will be any significant performance change with any of this options.
(IMO) The third option is the most readable option and closest to dynamic memory allocation like C# etc'. But this is my humble opinion, Choose what you like the most.

If it really bothers you and you can't sleep without an answer, test it with jsPerf.


@Chad made a jsPerf so you can sleep well tonight...

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 2
    Assigning a value at declaration can be nearly 60% faster than declaring then assigning ([jsPerf](http://jsperf.com/var-type-comparison)) – Chad Mar 12 '12 at 18:37
  • @Chad. Added your `jsPerf`. Note that in `chrome` **all** the results are **exactly** the same! – gdoron Mar 12 '12 at 18:44
  • @Chad I've run that test a year later in Chrome 29, FF 23 and IE 10.0 and also saw that all results were within the margin of error (i.e. exactly the same). – T Nguyen Sep 08 '13 at 16:57
  • Yup, There was a small difference in FF prior to v20. After that, it is the same speed in all browsers. No difference! – Chad Sep 08 '13 at 20:12
  • 1
    Source code should be readable, let the minifier/compiler tool of your choice do the dirty job. – Jens Mar 05 '14 at 19:53
  • upvote for sound advice _premature optimization is the root of all evil_ – Prakash K Jul 21 '17 at 07:22
6

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.

Marshall
  • 4,716
  • 1
  • 19
  • 14
1

In Chrome, execution times are identical.

The only real consideration here is optimizing network transfer.

Consider var a=1;var b=2;...;var z=9; versus var a=1,b=2,...,z=9;

If you put a ;var  in front of each identifier, that's 5 bytes (assuming a single-byte character encoding), versus 1 byte for a ,. Thus, declaring 26 variables, you can save 100 bytes by writing var  once and listing identifiers with commas.

Granted it's not a huge savings, but every byte helps when it comes to pushing bits over the network. It's not something to worry a great deal about, but if you find yourself declaring several variables in the same area, using the variable declaration list is an easy way to shave a few bytes off your JS file.

josh3736
  • 139,160
  • 33
  • 216
  • 263
0

That seems like premature optimization, the root of all evil.

How many times will it be executed? What fraction of of the whole program will this consume?

Ayman
  • 11,265
  • 16
  • 66
  • 92
0

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]);
    }
    ...
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • JavaScript is completely synchronous, not asynchronous. – Wk_of_Angmar Apr 09 '13 at 02:01
  • @Wk_of_Angmar, you've missed the point. JavaScript when executed is synchronous, however most of the code is run asynchronously. The vast majority of the time, the vast majority of JavaScript is simply waiting around for the browser to tell it that something happened, just so that it can execute for a couple hundredths of a millisecond. – zzzzBov Apr 09 '13 at 03:04
0

They all basically do the same thing: declare a variable and eventually define it (assign something to it). The only thing you're changing throughout your examples is the order in which that occurs, and even that depends on the browser that is compiling your JavaScript -- some might perform optimizations that others do not.

There are some stylistic guidelines you should follow though, and this answer explains them well. Keep in mind that that answer is technology agnostic and may not apply to JavaScript at all.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
0

Just stay away from option 1 if possible, there is no need to make two assignments.

Even variables declared inside a for loop or other compound statement/block will be available outside its containing block.

You can also do:

function MyFunction() {

  var a = SomeValue, b = SomeVavlue2;

}
yas
  • 3,520
  • 4
  • 25
  • 38