Javascript for..in vs for loop performance

前端 未结 4 676
忘了有多久
忘了有多久 2020-11-30 11:36

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         


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-30 11:51

    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/

提交回复
热议问题