declaring for-loop variable best practice - javascript

My question is more a curiosity question on for-loop style.
While reading some old code by others, I encountered a style I haven't seen before.
var declaredEarlier = Array
for(var i=0, length=declaredEarlier.length; i < length; i++) {
//stuff
}
I had never seen declaring a length before use and since this is an old app, was this kind of style a C/C++/old Java carryover? or was this developer unique?
Is there any benefit for declaring length that way instead of doing what I normally do:
for(var i=0; i < declaredEarlier.length; i++) {
//stuff
}
If this has been asked before, I could not find it. And if it's not stackoverflow applicable, which forum would be better to ask?

There are two reasons you might grab the length up-front like that:
In case the length may change (remember, JavaScript arrays aren't really arrays* and their length is not fixed) and you want to use the original length to limit the loop, or
To avoid repeatedly looking up the length on the object, since you know it's not going to change
The first is obviously substantive; the second is style and/or micro-optimisation.
* Disclosure: That's a link to a post on my anemic little blog.

for the first style the value of declaredEarlier can change so you need to use it
like that length=declaredEarlier.length
but for the second style you already know the value you dont need to calculate it again

Related

Javascript For-Loop Condition Caching

I've put together a jsperf test that compares for loops that iterate over an array with caching the array length condition vs not caching. I thought that caching the variable before to avoid recalculating the array length each iteration would be faster, but the jsperf test says otherwise. Can someone explain why this is? I also thought that including the array length variable definition (when cached) within the for loop's initialization would reduce the time since the parse doesn't need to look up the "var" keyword twice, but that also doesn't appear to be the case.
example without caching:
for(var i = 0; i < testArray.length; i++){
//
}
example with caching
var len = testArray.length;
for(var i = 0; i < len; i++){
//
}
example with caching variable defined in for loop initialization
for(var i = 0, len=testArray.length; i < len; i++){
//
}
http://jsperf.com/for-loop-condition-caching
Can someone explain why this is?
This optimization and case is extremely common so modern JavaScript engines will automatically perform this optimization for you.
Some notes:
This is not the case when iterating a NodeList (such as the result of querySelectorAll
This is an overkill micro optimization for most code paths anyway, usually the body of the loop takes more time than this comparison anyway.
The performance of the scenarios that you posted depends on how smart the JS engine's optimizer is. An engine with a very dump optimizer (or no optimizer at all) will likely be faster when you are using the variable, but you can't even rely on that. After all, length's type is well-known, while a variable can be anything and may require additional checks.
Given a perfect optimizer, all three examples should have the same performance. And as your examples are pretty simple, modern engines should reach that point soon.

Is the following considered micro optimization

I am not very well parsed in javascript, but do you call the following micro optimization?
for(var j=0;j < document.getElementsByTagName('a').length; j++)
{
//...
}
var Elements = document.getElementsByTagName('a');
var ElementsLength = Elements.length;
for(var j=0;j < ElementsLength ; j++)
{
//...
}
var Elements = document.getElementsByTagName('a');
for(var j=0;j < Elements.length; j++)
{
//...
}
does document.getElementByTagName really get called in every loop
cycle in the first case?
do browsers try to optimize the javascript we write?
is there any difference between the second and third case considering
that the collection will never change?
does document.getElementByTagName really get called in every loop cycle in the first case?
Yes.
do browsers try to optimize the javascript we write?
It won't change it functionally. There's a difference between calling a function once and calling it every time in a loop; perhaps you meant to call the function every time. "Optimising" that away is actually changing what the program does.
is there any difference between the second and third case considering that the collection will never change?
Not functionally, but performance wise yes. Accessing the length attribute is a little more overhead than reading the number from a simple variable. Probably not so much you'd really notice, but it's there. It's also a case that cannot be optimised away, since Elements.length may change on each iteration, which would make the program behave differently. A good optimiser may be able to detect whether the attribute is ever changing and optimise in case it's certain it won't; but I don't know how many implementations really do that, because this can become quite complex.

Other ways to increment a variable in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?
I'm a big fan of Douglas Crockford and his excellent book, JavaScript: The Good Parts. I also use his JSLint tool on an hourly basis before checking in any code to our repository, as is good sense.
One thing I've noticed when running code through JSLint is its insistence that the ++ increment operator is somehow evil. I know I can turn certain rules off, but that's cheating ;). Crockford mentions his dislike on page 112 of JS: TGP...
In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don't use them any more. I think that as a result, my coding style has become cleaner.
That's all very lovely, but he doesn't give any examples of the way he codes them now. I assume he's doing something like...
var i;
i = 0;
i = i + 1;
Again, great, but I've got a few basic 'for loops' in my JS code, as I imagine many people have, and I've always used the standard syntax...
for (i = 0; i < myArray.length; i++) {
// Loop Stuff
}
Am I missing something? What's the cleanest and/or best way to increment/decrement?
I think this is rather controversial, and I personally stick to i++ in loops. Of cource, you can replace it with i = i + 1 in your loop statement, to be fully compliant to JSLint.
There aren't real alternatives to increment and decrement numerical values in JavaScript. You can often use Array.forEach() and/or Object.keys() in order to prevent numerical indexes.
The only tricky thing I see in autoincrement/decrement operators (and I'm quite surprised that no one here pointed that out) is the difference between prefix (++i) and postfix (i++) versions. I also believe that autoincrement/decrement operators are slightly more efficient, in general. Besides this, I think the choice is based mainly on aesthetics, especially in javascript.
to pass JSLint I now always do:
for (var i = 0; i < myArray.length; i+=1) {
// Loop Stuff
}
In C/C++ this is important, especially with arbitrary iterators and pre/post increment semantics. Also, random access vs forward-iterators.
In Javascript it's more about aesthetics than anything else. Unless you're dealing with strings. "1"+1 is "11".
I would say that ++i is an idiom that's worth being consistent with.
JSLint is wrong.
Personally, I see nothing wrong with the ++/-- operators for incrementing and decrementing. While something like i = i + 1; may be easier for new coders, the practice is not rocket science once you know what the operators stand for.
Regarding loop, one original idea can be using such loop to avoid all kinds of numbers:
var a = [];
for (var i in " ")
a.push("Loop iteration here");
alert(a.join("\n"));
Meaning iterate over a string, there will be amount of iterations equal to the string length - 5 in the above example.
Live test case: http://jsfiddle.net/vTFDP/

Javascript/HTML, is it possible to create variable names from a loop

Imagine i had: <div id names>142,140,150</names>
could i then (in Javascript) write a forloop which declares variable names, with these values appended ie
var list = document.getElementById('names').innerHTML.Split(',');
for(i=0; i<list.Length; i++){
var 'beginning' + list[i];
}
so i'd essentially want to create:
var beginning142
var beginning140
var beginning150
You can indeed:
window['beginning' + list[i]] = 'value';
Funny coincidence, I answered a very closely related question 10 seconds prior to this one, and then I used exactly this as an example. So a more elaborate explanation on why this works is available here.
You can do something like this:
for(var i = 0; i<100; i++)
{
eval("var beginning"+i);
}
For developers afraid from eval This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval()
everywhere. In fact, there are very few good use cases for running
eval() at all. There are definitely concerns with code clarity,
debugability, and certainly performance that should not be overlooked.
But you shouldn’t be afraid to use it when you have a case where
eval() makes sense. Try not using it first, but don’t let anyone scare
you into thinking your code is more fragile or less secure when eval()
is used appropriately.
I can't add comment to your question due to low reputation score - this is not answer but advice.
I think It would be better to create single array with your keys 142,140,150...
Why don't you define an object that has those values as an attribute on it.
For example:
var myVariable = function(id, value){
this.Id = id;
this.Value = value;
};
then you can just instantiate this object. I think it is less complicated and more readable in the end.

How expensive are JS function calls (compared to allocating memory for a variable)?

Given some JS code like that one here:
for (var i = 0; i < document.getElementsByName('scale_select').length; i++) {
document.getElementsByName('scale_select')[i].onclick = vSetScale;
}
Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?
I am not sure how large the effect is in real life, with the result from getElementsByName typically having < 10 items. I'd like to understand the underlying mechanics anyway.
Also, if there's anything else noteworthy about the two options, please tell me.
Definitely. The memory required to store that would only be a pointer to a DOM object and that's significantly less painful than doing a DOM search each time you need to use something!
Idealish code:
var scale_select = document.getElementsByName('scale_select');
for (var i = 0; i < scale_select.length; i++)
scale_select[i].onclick = vSetScale;
Caching the property lookup might help some, but caching the length of the array before starting the loop has proven to be faster.
So declaring a variable in the loop that holds the value of the scale_select.length would speed up the entire loop some.
var scale_select = document.getElementsByName('scale_select');
for (var i = 0, al=scale_select.length; i < al; i++)
scale_select[i].onclick = vSetScale;
A smart implementation of DOM would do its own caching, invalidating the cache when something changes. But not all DOMs today can be counted on to be this smart (cough IE cough) so it's best if you do this yourself.
In principle, would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?
yes.
Use variables. They're not very expensive in JavaScript and function calls are definitely slower. If you loop at least 5 times over document.getElementById() use a variable. The idea here is not only the function call is slow but this specific function is very slow as it tries to locate the element with the given id in the DOM.
There's no point storing the scaleSelect.length in a separate variable; it's actually already in one - scaleSelect.length is just an attribute of the scaleSelect array, and as such it's as quick to access as any other static variable.
I think so. Everytime it loops, the engine needs to re-evaluate the document.getElementsByName statement.
On the other hand, if the the value is saved in a variable, than it allready has the value.
# Oli
Caching the length property of the elements fetched in a variable is also a good idea:
var scaleSelect = document.getElementsByName('scale_select');
var scaleSelectLength = scaleSelect.length;
for (var i = 0; i < scaleSelectLength; i += 1)
{
// scaleSelect[i]
}

Categories