Javascript 'var variable' inside loop vs outside. Any difference in performence - javascript

for(var i=0;i<lines.length;i++) {
var line = lines[i];
vs
var line;
for(var i=0;i<lines.length;i++) {
line = lines[i];
Do this two snippets have different performance. If yes, please explain why.

I have run a benchmark on this and have found that there is pretty much no difference in performance.
If you would like to recreate it:
var lines = new Array(#BIG_NUMBER#);
lines.fill(#BIG_OBJECT#);
var a = (new Date()).getTime();
for(var i=0;i<lines.length;i++) {
var line = lines[i]; }
var b = (new Date()).getTime();
var line;
for(var i=0;i<lines.length;i++) {
line = lines[i]; }
var c = (new Date()).getTime();
console.log("a:" + (b-a) + " b:" + (c-b));
This makes sense, as there is almost no difference, both cases will create a local object that will be stored, and will be reassigning it multiple times.

Your code will work differently in both the cases.
In the first one line is a global variable an will be accessible outside the for loop, which is not the case in second one.
So I don't think performance comparison makes any sense here!
Even then, declaring a variable again and again is unnecessary though I don't think it is a complex operation. But yes declaring it repetitively will deteriorate the performance.

Related

Is a deep object slow in JavaScript? If so how much

Simple question: is there a merit of using a shallow object over a deeper one?
When I write a code, I tend to use a deep object just so it is easy to understand and classify. But I am wondering if this custom is making my code slower.
I have done a test but I have no idea if I am doing it correctly.
//building necessary objects
var a = {};
var b;
b = a;
for (var i = 0; i < 100; i++) {
b["a"] = {};
b = b["a"];
}
var c = {};
//objects used
//a.a.a. ..(101 "a"s).. .a === {}
//c === {}
//1st test: shallow
var d;
var start = performance.now();
for (var i = 0; i < 1000000000; i++) {
d = c;
d = null;
}
var end = performance.now();
console.log('Shallow: ' + (end - start));
//2nd test: deeper
var e;
var start = performance.now();
for (var i = 0; i < 1000000000; i++) {
e = a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a;
e = null;
}
var end = performance.now();
console.log('Deeper: ' + (end - start));
the result(ms):
shallow 3229 3304 3246 3253 3277
deep 3375 3343 3247 3193 3248
The test times for the deep object is not slow, but sometimes even faster than the shallow one.
Despite the result, I am not confident enough to conclude that they are the same speed.
Is there any difference between two of them?
You are using unrealistic code to test "real code", which is nonsense
You use Date.now() which is approximation to timestamp and you should use performance.now() to test js speed. Currently, even with good test code, you get wrong results.
JS engines are updating all the time. There were times when deep objects were slow, it's not a case anymore for the last x years. It's such an old problem that I can't even remember the years or google anything valuable out.
It is an optimisation in the js engine to access objects directly and allow for deep objects to be cashed in a variable which takes less time to reach. So it is faster to access them without having to go through the chain.
For example:
var a={a:{a:{}}}
var b=a.a.a
var c=b
// is faster than
var c=a.a.a
For more information read this: JavaScript Performance: Mutiple variables or one object?

var assignment and declaration using a single var and commas? [duplicate]

In JavaScript, it is possible to declare multiple variables like this:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...or like this:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
Is one method better/faster than the other?
The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.
With the second way, it is annoying to remove the first or last declaration because they start from the var keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.
Besides maintainability, the first way eliminates possibility of accident global variables creation:
(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());
While the second way is less forgiving:
(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
variable2 = "Testing...", // Becomes a global variable
variable3 = 42; // A global variable as well
}());
It's much more readable when doing it this way:
var hey = 23;
var hi = 3;
var howdy 4;
But takes less space and lines of code this way:
var hey=23,hi=3,howdy=4;
It can be ideal for saving space, but let JavaScript compressors handle it for you.
ECMAScript 2015 introduced destructuring assignment which works pretty nice:
[a, b] = [1, 2]
a will equal 1 and b will equal 2.
It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.
It's just a matter of personal preference. There is no difference between these two ways, other than a few bytes saved with the second form if you strip out the white space.
Maybe like this
var variable1 = "Hello, World!"
, variable2 = 2
, variable3 = "How are you doing?"
, variable4 = 42;
Except when changing the first or last variable, it is easy to maintain and read.
Use the ES6 destructuring assignment: It will unpack values from arrays, or properties from objects, into distinct variables.
let [variable1 , variable2, variable3] =
["Hello, World!", "Testing...", 42];
console.log(variable1); // Hello, World!
console.log(variable2); // Testing...
console.log(variable3); // 42
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
is more readable than:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
But they do the same thing.
My only, yet essential, use for a comma is in a for loop:
for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}
I went here to look up whether this is OK in JavaScript.
Even seeing it work, a question remained whether n is local to the function.
This verifies n is local:
a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
var e = a[i];
console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
"as expected, n was local" : "oops, n was global");
For a moment I wasn't sure, switching between languages.
Although both are valid, using the second discourages inexperienced developers from placing var statements all over the place and causing hoisting issues. If there is only one var per function, at the top of the function, then it is easier to debug the code as a whole. This can mean that the lines where the variables are declared are not as explicit as some may like.
I feel that trade-off is worth it, if it means weaning a developer off of dropping 'var' anywhere they feel like.
People may complain about JSLint, I do as well, but a lot of it is geared not toward fixing issues with the language, but in correcting bad habits of the coders and therefore preventing problems in the code they write. Therefore:
"In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function." - http://www.jslint.com/lint.html#scope
Another reason to avoid the single statement version (single var) is debugging. If an exception is thrown in any of the assignment lines the stack trace shows only the one line.
If you had 10 variables defined with the comma syntax you have no way to directly know which one was the culprit.
The individual statement version does not suffer from this ambiguity.
I think it's a matter of personal preference. I prefer to do it in the following way:
var /* Variables */
me = this, that = scope,
temp, tempUri, tempUrl,
videoId = getQueryString()["id"],
host = location.protocol + '//' + location.host,
baseUrl = "localhost",
str = "Visit W3Schools",
n = str.search(/w3schools/i),
x = 5,
y = 6,
z = x + y
/* End Variables */;
The maintainability issue can be pretty easily overcome with a little formatting, like such:
let
my_var1 = 'foo',
my_var2 = 'bar',
my_var3 = 'baz'
;
I use this formatting strictly as a matter of personal preference. I skip this format for single declarations, of course, or where it simply gums up the works.
As everyone has stated it is largely preference and readability, but I'll throw a comment on the thread since I didn't see others share thoughts in this vein
I think the answer to this question is largely dependent on what variables you're setting and how they're related. I try to be consistent based on if the variables I'm creating are related or not; my preference generally looks something like this:
For unrelated variables
I single-line them so they can be easily moved later; I personally would never declare unrelated items any other way:
const unrelatedVar1 = 1;
const unrelatedVar2 = 2;
const unrelatedVar3 = 3;
For related things (utility)
If I'm creating new variables I declare as a block -- this serves as a hint that the attributes belong together
const
x = 1,
y = 2,
z = 3
;
// or
const x=1, y=2, z=3;
// or if I'm going to pass these params to other functions/methods
const someCoordinate = {
x = 1,
y = 2,
z = 3
};
this, to me, feels more consistent with de-structuring:
const {x,y,z} = someCoordinate;
where it'd feel clunky to do something like (I wouldn't do this)
const x = someCoordiante.x;
const y = someCoordiante.y;
const z = someCoordiante.z;
For related things (construction)
If multiple variables are created with the same constructor I'll often group them together also; I personally find this more readable
Instead of something like (I don't normally do this)
const stooge1 = Person("moe");
const stooge2 = Person("curly");
const stooge3 = Person("larry");
I'll usually do this:
const [stooge1, stooge2, stooge3] = ["moe", "curly", "larry"].map(Person);
I say usually because if the input params are sufficiently long that this becomes unreadable I'll split them out.
I agree with other folk's comments about use-strict
The concept of "cohesion over coupling" can be applied more generally than just objects/modules/functions. It can also serve in this situation:
The second example the OP suggested has coupled all the variables into the same statement, which makes it impossible to take one of the lines and move it somewhere else without breaking stuff (high coupling). The first example he gave makes the variable assignments independent of each other (low coupling).
From Coupling:
Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability.
So choose the first one.
I believe that before we started using ES6, an approach with a single var declaration was neither good nor bad (in case if you have linters and 'use strict'. It was really a taste preference. But now things changed for me. These are my thoughts in favour of multiline declaration:
Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations.
ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.
I think the first way (multiple variables) is best, as you can otherwise end up with this (from an application that uses KnockoutJS), which is difficult to read in my opinion:
var categories = ko.observableArray(),
keywordFilter = ko.observableArray(),
omniFilter = ko.observable('').extend({ throttle: 300 }),
filteredCategories = ko.computed(function () {
var underlyingArray = categories();
return ko.utils.arrayFilter(underlyingArray, function (n) {
return n.FilteredSportCount() > 0;
});
}),
favoriteSports = ko.computed(function () {
var sports = ko.observableArray();
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
sports.push(a);
}
});
});
return sports;
}),
toggleFavorite = function (sport, userId) {
var isFavorite = sport.IsFavorite();
var url = setfavouritesurl;
var data = {
userId: userId,
sportId: sport.Id(),
isFavourite: !isFavorite
};
var callback = function () {
sport.IsFavorite(!isFavorite);
};
jQuery.support.cors = true;
jQuery.ajax({
url: url,
type: "GET",
data: data,
success: callback
});
},
hasfavoriteSports = ko.computed(function () {
var result = false;
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
result = true;
}
});
});
return result;
});
A person with c background will definitely use the second method
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
the above method is more look like in c language
The main problem with the second one is that no IDE to date is respecting this style.
You cannot fold these structures.
We can use all the approaches, there is no need to go with one or the other. Applying different approaches can make the code easier to read.
I'll show real examples from one of my Vue.js 3 projects:
Example 1
const [store, route] = [useStore(), useRoute()]
const
showAlert = computed(() => store.getters['utils/show']),
userIsLogged = computed(() => store.getters['auth/userIsLogged']),
albumTitle = computed(() => store.getters['albums/title']);
Example 2
const
store = useStore(),
username = ref(''),
website = ref(''),
about = ref('');
const
isAppFirstRender = computed(() => store.getters['utils/isAppFirstRender']),
showToast = ref(false);
As you can see above, we can have small chunks of variable declarations. There is no need to declare big chunks. If I have let's say 12 variables I could group them in a way that makes sense or looks easier to read, without the verbosity:
const
numberOne = 5,
numberTwo = 10,
numberThree = 15;
const
stringOne = 'asd',
stringTwo = 'asd2',
stringThree = 'asd3';
let [one, two, three] = [1,2,3]
Ofcourse, everyone has their own style. This is my personal preference, using a mix of all approaches.
I personally don't like verbosity. I like code that has what it needs and not more.
Is a very nice feature. And no reason to avoid. As technology evolves, we must evolve our selves. This feature exists in some languages as Perl, for long time. For instance building a WebGL mesh, new javascript style
//initialize vertices with some calculated points
[verts[ix], verts[iy], verts[iz]] = ps[0];
[verts[ix + 3], verts[iy + 3], verts[iz + 3]] = ps[1];
[verts[ix + 6], verts[iy + 6], verts[iz + 6]] = ps[2];
//initializing normals with cross products
[norms[ix], norms[iy], norms[iz]] = cr;
[norms[ix + 3], norms[iy + 3], norms[iz + 3]] = cr;
[norms[ix + 6], norms[iy + 6], norms[iz + 6]] = cr;
And as a mater of fact, the old style code, it is much harder to debug, and by far much harder to understand and to find any bugs than above one. And this goes a lot, this sample is oversimplified. Lots of repetitive routines hindering the real logic, making code looking like some kind of magic. Same as above, but ancient style:
//initialize vertices with some calculated points
verts[ix] = ps[0][0];
verts[iy] = ps[0][1];
verts[iz] = ps[0][2];
verts[ix + 3] = ps[1][0];
verts[iy + 3] = ps[1][1];
verts[iz + 3] = ps[1][2];
verts[ix + 6] = ps[2][0];
verts[iy + 6] = ps[2][1];
verts[iz + 6] = ps[2][2];
//initializing normals with cross products
norms[ix] = cr[0];
norms[iy] = cr[1];
norms[iz] = cr[2];
norms[ix + 3] = cr[0];
norms[iy + 3] = cr[1];
norms[iz + 3] = cr[2];
norms[ix + 6] = cr[0];
norms[iy + 6] = cr[1];
norms[iz + 6] = cr[2];
Note, while migrating my code new style, I not only heavily deleted big blocks of routine code. I easily spotted inconsistencies that escaped lots of code reviews, just because of making the code much more easy to visualize, more laconic and logic oriented and much less routine oriented.

Speed up javascript run time

Although I have reviewed several of previous posts, my rookie capabilities are blind to a solution for speeding up the execution of the following code. There are hundreds of k, and for each k there are (tens)thousands of i and nearSum() has a loop that evaluates testStr.
This code is slow and timing out Chrome – how do I improve the execution?
Before you ask, the only reason for any of the code is ‘because it is working’. The values for nn are global variables.
Function()…
resArrLen = resultArray[k].length;
for (i=0;i<resArrLen;i++)
{
testStr = resultArray[k][i].toString();
resultArray[k][i] = testStr + "'" + nearSum(testStr);
}//end for i
…
function nearSum(seqFrag)
{
var i=0;
var ninj=0;
var seqFragLen=0;
var calcVal=0;
var nn="";
//sum values
seqFragLen = seqFrag.length;
for (i=0; i+1<seqFragLen; i++)
{
nn = seqFrag.substr(i,2); //gets value
ninj = eval(nn);
calcVal = calcVal.valueOf() + ninj.valueOf();
} //end for i
return calcVal.toFixed(2);
} //end nearSum
For one thing, it appears that you are using 'eval' to convert a string to a number. That's not how that's intended to be used. Use 'Number(nn)' or 'parseInt(nn)' instead.
Otherwise, the code is incomplete and with no example data it's difficult to optimize.

Free the counter variable when a while loop exits in JavaScript

I've found that when making masses of objects in JavaScript, the while loop is the best tool to tune performance.
I get the best speed when writing my loop like this:
var i = array.length
while (i--) {
// Do stuff
}
However, if I want to nest a while loop, I have to use a different variable name, otherwise the counter breaks:
var i = array1.length
while (i--) {
var i = array2.length
while (i--) {
// NOPE THE COUNTER IS NOW BROKEN
}
}
Some have suggested j, but then why not start the first array with a variable called a and go up form there?
What's the best practice in this situation?
Is there a way to delete the variable so it isn't available in the secondary scope?
The use of i and j (followed by k if you are nesting that deep) are standard idioms shared by many programming languages. (In fact, the use of i as a loop variable goes back to ForTran.)
By using i and j, anyone reading your code should realize those are standard loops and loop counters. Using a makes the reader stop and ponder over "Why was that used?"
Now, to answer your question:
In Javascript, you could reuse the variable i if you wanted to by using an anonymous function - but this is
Not standard practice
An anti-pattern -- AKA dumb
Slower to execute.
--
var i = 10;
while (i--) {
(function() {
// New function, this is a new `i`, completely masking the original.
var i = 20;
while(i--) {
}
{();
}
You need variable scope here. In C, you can create variable scope with block:
int i = 1;
{
int i = 2;
printf("inner i = %d\n", i);
}
printf("outer i = %d\n", i);
//=>
inner i = 2
outer i = 1
However, in javascript, block doesn't create new variable scope, but shares the outer one. You'll need function to create a new variable scope.
var i = 2;
while (i--) {
console.log("outer i = " + i);
(function () {
var i = 3;
while (i--) {
console.log("inner i = " + i);
}
})();
}
//=>
outer i = 1
inner i = 2
inner i = 1
inner i = 0
outer i = 0
inner i = 2
inner i = 1
inner i = 0

What is optimal method for accessing function parameters in javascript?

Of these similar function definitions, what is optimal way to access arguments and why?
function DoStuff()
{
return arguments[0] + arguments[1] + arguments[2];
}
function DoStuff(first, second, third)
{
return first + second + third;
}
Does one allocate less memory than the other? Is one faster to access the parameter values than the other?
Here is my test:
function Test1()
{
var start = new Date();
for (var i = 0; i < 1000000; i++)
{
DoStuff1(i, i + 1, i + 2);
}
var done = new Date();
alert(done - start);
}
function Test2()
{
var start = new Date();
for (var i = 0; i < 1000000; i++)
{
DoStuff2(i, i + 1, i + 2);
}
var done = new Date();
alert(done - start);
}
function DoStuff1()
{
var result = arguments[0] + arguments[1] + arguments[2];
}
function DoStuff2(first, second, third)
{
var result = first + second + third;
}
Here are the results:
IE FF
Test1()
2355 402
2381 395
2368 392
Test2()
504 6
507 7
505 7
I figured that test 2 would be faster but it's drastically faster. So, not only is it more readable but it's more efficient.
Forget about performance in this case and go for readability. From that perspective, option (2) is much to be preferred -- though, I'd go for more descriptive names. ;-)
The second.
Using the second, you know based on the signature exactly what is expected when you call the method. It's also far easier for maintainability in the future.
Referencing arguments[] anywhere in a function will significantly decrease performance on many browsers.
The performance difference should be fairly negligible between the two, however the readability of named parameters is a better practice. There are times when you cannot use named parameters and in those cases I typically use a big block of script to unpack arguments into named locals.

Categories

Resources