Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript var statement and performance

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.

like image 314
frenchie Avatar asked Mar 12 '12 18:03

frenchie


People also ask

Should you use VAR in JavaScript anymore?

This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.

Is VAR faster than const?

The execution context underlying how the JavaScript interpreter runs the code is basically the same when you use var compared to when you use let and const . That results in the same execution speed.

What is the problem with VAR in JavaScript?

“var” has no block scope As we can see, var pierces through if , for or other code blocks. That's because a long time ago in JavaScript, blocks had no Lexical Environments, and var is a remnant of that.

Is VAR slower than let?

After testing this in Chrome and Firefox, this shows that let is faster than var , but only when inside a different scope than the main scope of a function. In the main scope, var and let are roughly identical in performance. In IE11 and MS Edge, let and var are roughly equal in performance in both cases.


1 Answers

"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...

like image 151
gdoron is supporting Monica Avatar answered Oct 21 '22 05:10

gdoron is supporting Monica