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
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/