I was clustering around 40000 points using kmean algorithm. In the first version of the program I wrote the euclidean distance function like this
var euclide
The For/In loop, simply loops through all properties in an object. Since you are not specifying the number of iterations the loop needs to take, it simply 'guesses' at it, and continues on until there are no more objects.
With the second loop, you are specifying all possible variable... a)a starting point, b) the number of iterations the loop should take before stopping, c) increasing the count of the starting point.
You can think of it this way... For/In = guesses the number of iterations, For(a,b,c) you are specifying
Look at what's happening differently in each iteration:
for( var i = 0; i < p1.length; i++ )
i < p1.length
i
by oneVery simple and fast.
Now look at what's happening in each iteration for this:
for( var i in p1 )
Repeat
- Let P be the name of the next property of obj whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V, empty).
It has to find next property in the object that is enumerable. With your array you know that this can be achieved by a simple integer increment, where as the algorithm to find next enumerable is most likely not that simple because it has to work on arbitrary object and its prototype chain keys.
As a side note, if you cache the length of p1:
var plen = p1.length;
for( var i = 0; i < plen; i++ )
you will get a slight speed increase.
...And if you memoize the function, it will cache results, so if the user tries the same numbers you will see a massive speed increase.
var eDistance = memoize(euclideanDistance);
function memoize( fn ) {
return function () {
var args = Array.prototype.slice.call(arguments),
hash = "",
i = args.length;
currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ?
JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize = {});
}
return (hash in fn.memoize) ? fn.memoize[hash] :
fn.memoize[hash] = fn.apply(this, args);
};
}
eDistance([1,2,3],[1,2,3]);
eDistance([1,2,3],[1,2,3]); //Returns cached value
credit: http://addyosmani.com/blog/faster-javascript-memoization/
First You should be aware of this in the case of for/in and arrays. No big deal if You know what You are doing.
I run some very simple tests to show the difference in performance between different loops: http://jsben.ch/#/BQhED
That is why prefer to use classic for loop for arrays.