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.
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.
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.
“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.
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.
"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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With