Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables using single or multiple var statements. Performance wise

(Question moved from Webmasters.)

Someone once told me that it's better for Javascript performance to use one var statement rather then multiple.

I.e.

// Version A. Allegedly Faster
var a = 1,
    b = 2,
    c = 3;

// Version B. Allegedly Slower
var a = 1;
var b = 2;
var c = 3;

The reasoning behind this was along the lines of: For every var statement, Javascript will start allocating memory and then stop at the semicolon. Whereas, if you have only one var statement, many JS implementations will optimize it and allocate space for all variables in the same call. Thus making things go faster.

However, when googling to confirm this I only find rants about how some consider the second example to be simpler from a maintenance point of view. And some disagree. This JSPerf test sais there is no difference.

So my question: From a performance perspective, is there any reason version A or B would be better?

(You do save a few bytes on not writing the "var" declaration, but that is in delivery of data to a browser. This question includes server side JS)

like image 623
Skurpi Avatar asked Mar 30 '14 10:03

Skurpi


1 Answers

First of all, your question is not answerable without specifying what JavaScript implementation is concerned. Performance is not the concern of the language and anyone could write a conforming JavaScript implementation where separate var statements would be slower because performance characteristics are not specified in the language specification.

You mentioned server side so I'm going to assume V8, which has 2 different compilers for JavaScript.

The first compiler would parse your source code into an AST and then walk the tree's nodes while spitting machine instructions for each tree node. So no, the syntactic form of your var statements could have not affected the performance here.

The second compiler is much smarter and takes its time to analyze the code through multiple different representations (not just AST) in order to generate optimized code. Since the dumb compiler can already see that the codes have the same semantics, so can the smart one, so there is again no difference.

Syntactic differences where semantics are exactly the same will not in general have any performance difference unless there is a bug. But this is a trivial case so I would find it very hard to believe any world class JavaScript implementation failing here.

like image 143
Esailija Avatar answered Sep 28 '22 02:09

Esailija