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?
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.
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.
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.
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.
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.
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').
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