Comparing javascripts native "for loop" for each () prototype

So, I had a debate with one engineer about a loop in JavaScript. The problem was building native for the loop and a prototype of each () method. Now I know that there are many documents / blogs for each and for each, but this debate is somewhat different, and I would like to hear what some of you think.

Take the following loop, for example

Example 1

var someArray = [blah, blah, blah,...,N]; var length = someArray.length; for(var index = 0; index < length; index++){ var value = someFunction(someArray[index]); var someOtherValue = someComplicatedFunction(value, someArray[index]); //do something interesting... } 

For me this happens to be second nature, mainly because I learned how to code C , and it transferred me. Now I use For-each in both C # and Java (carry me, I know that we are talking about JavaScript here ..), but whenever I hear about loops, First I think about this guy. Now consider the same example written using Prototype each ()

example 2

 var someArray = [blah, blah, blah,…..,N]; someArray.each(function(object){ var value = someFunction(object); var someOtherValue = someComplicatedFunction(value, object); //do something interesting... }); 

In this example, right off the bat, we see that the design has less code, but I think every time we scroll through the object, we must create a new function to solve the operation in question. Thus, it will be bad to bring down collections with a large number of objects. So my buddy argument was that Example 2 is much easier to understand and actually cleaner than Example 1 because of its functional approach. My argument is that any programmer should be able to understand Example 1, since it is studied in programming 101. Thus, the lighter argument is not applied, and Example 1 works better than Example 2 . Then why bother with # 2 . Now, after reading it, I found out that when the size of the array is small, the overhead for example 2 is negligible. However, people kept talking about the lines of code you write less and that Example 1 is error prone. I still do not buy these reasons, so I wanted to know what you guys think ...

+4
source share
5 answers

In the second example, you are not creating a new function at each iteration. There is only one function that constantly calls the call again and again. To clarify the point of only one function used, consider how you yourself implement the each method.

 Array.prototype.each = function(fn) { for(var i = 0; i < this.length; i++) { // if "this" should refer to the current object, then // use call or apply on the fn object fn(this[i]); } } // prints each value (no new function is being created anywhere) [1, 2, 3].each(function(v) { console.log(v); }); 

Of course, there is overhead for calling a function in the first place, but if you are not dealing with massive collections, this is not a problem in modern browsers.

Personally, I prefer the second approach for the simple reason that it frees me from worrying about unnecessary details that I should not worry about in the first place. Say, if we iterate over a collection of employee objects, then the index is just an implementation detail, and in most cases, if not all, you can distract the programmer from constructs such as the each method in Prototype, which is now the standard in JavaScript, since it was included in ECMAScript 5th ed called forEach .

 var people = [ .. ]; for(var i /* 1 */ = 0; i /* 2 */ < people.length; i++ /* 3 */) { people[i /* 4 */].updateRecords(); people[i /* 5 */].increaseSalary(); } 

We noted all 5 occurrences of all i in a row with comments. We could easily remove the i index at all.

 people.forEach(function(person) { person.updateRecords(); person.increaseSalary(); }); 

For me, the advantage is not in smaller lines of code, but the removal of unnecessary details from the code. This is the same reason most programmers jumped on the iterator in Java when it was available, and then in the enhanced for loop when it came out. The argument that the same reasons are not suitable for JavaScript is simply not applicable.

+3
source

I am sure that it does not create a new code function for each iteration, but rather calls a function on each of them. This may include a bit more overhead to track the iterator domestically (some languages ​​allow you to change the list, and some not), but it should not be very different from the procedural version.

But anytime, when you ask, which is faster, you should ask, does it really matter? Have you put a code profiler on it and tested it with real-world data? You can spend a lot of time figuring out which one is faster, but if it only accounts for 0.0001% of your lead time, who needs it? Use profiling tools to find bottlenecks that really matter, and use any iteration method that you and your team agree is easier to use and read.

+2
source

Example 1 is not only error prone, for arrays of trivial length it is a bad choice - and everyone (or forEach, as defined in JavaScript 1.6, but IE8 still doesn't support it) is definitely the best choice in style.

The reason for this is simple: you tell the code what to do, not how to do it. In my tests with firefox, the forEach method is about 30% of the speed as a for loop. But when you make miniature arrays, this is not even so important. It is much better to make your code cleaner and more understandable (remember: what it does, not how to do it), not only for your sanity the next time you come back to it, but also for the common sense of anyone who looks at your code .

If the only reason you include the prototype is because of the .each method, you are doing it wrong. If all you need is a clean iteration method, use the .forEach method, but remember to define your own. This is from the MDC on forEach page - a useful check to give you the .forEach method if it does not exist:

 if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this); } }; } 

You can tell how this works, that no new function is created for each element, although it is called for each element.

+2
source

The answer is its subjective.

For me, Example 2 is actually NOT ONLY much smaller code, and also includes loading (throughput) and parsing / executing (runtime) the ~ 30kb library before you can use it - therefore, not only the method itself less effective in itself, it is also associated with installation overhead. For me - arguing that Example 2 is better - this is insanity - however, this is just an opinion that many (and quite right) will not completely agree.

0
source

The IMO second approach is concise and easy to use, although it becomes complicated (see the prototype document) if you want to use things like break or continue . See the documentation for each .

So, if you use a simple iteration, using each () is better than IMO, as it can be more concise and understandable, although its less efficient than raw for a loop

0
source

All Articles