Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop improved with ">>>" operator?

I'm updating mootools from 1.3.2 to 1.4.1. I saw a strange change. From this

for (var i = 0, l = this.length; i < l; i++){....

to this

for (var i = 0, l = this.length >>> 0; i < l; i++){

how the ">>>" operator, used in that way, can improve performance? What do you think about it?

like image 473
Antonio Avatar asked Nov 24 '11 10:11

Antonio


People also ask

What is enhanced for loop?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

What are the 3 arguments of the for loop?

For Loop ArgumentsCondition: The condition determines the end of the loop. The conditional statement will evaluate as either true or false. The loop runs until the condition returns false. Increment/Decrement: This increases or decreases the initializer by one each time the condition returns true.

How does nested for loop work?

When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

Why we use nested loop?

Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. For example, you read a file line by line and for each line you must count how many times the word “the” is found.


2 Answers

The >>> bitwise operator is bounded between and including 0 and 2^32-1 (4,294,967,295). By using using >>>, the framework ensures that the loop does not execute near-infitite times.

PS. The context of the code:

Array.implement({every: function(fn, bind){
    for (var i = 0, l = this.length >>> 0; i < l; i++){
        if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
    }

Since i is initialised at zero, and incremented by an integer 1, and the length property is always an integer, there are no negative side-effects. Another application of the >>> method is rounding, to convert a decimal number to an integer.

like image 199
Rob W Avatar answered Oct 25 '22 02:10

Rob W


I guess the reason is some kind of conversion to make sure that the value is always numeric (as opposed to eg. the string '2').

like image 22
erikkallen Avatar answered Oct 25 '22 02:10

erikkallen