Javascript for..in vs for loop performance [英] Javascript for..in vs for loop performance

查看:122
本文介绍了Javascript for..in vs for loop performance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用kmean算法聚集了大约40000点。在程序的第一个版本中,我写了这样的欧几里德距离函数

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 euclideanDistance = function( p1, p2 ) { // p1.length === p2.length == 3
    var sum = 0;
    for( var i in p1 ){
        sum += Math.pow( p1[i] - p2[i], 2 );
    }
    return Math.sqrt( sum );
};

总体程序非常缓慢,平均需要7秒才能执行。经过一些分析后,我重写了上述函数,如下所示

The overall program was quite slow taking on average 7sec to execute. After some profiling I rewrote the above function like this

var euclideanDistance = function( p1, p2 ) { // p1.length === p2.length == 3
    var sum = 0;
    for( var i = 0; i < p1.length; i++ ) {
        sum += Math.pow( p1[i] - p2[i], 2 );
    }
    return Math.sqrt( sum );
};

现在程序平均需要400毫秒左右。由于我编写for循环的方式,这是一个巨大的时间差异。我通常不会为数组使用 for..in 循环,但出于某种原因我在编写此函数时使用它。

Now the programs on average take around 400ms. That's a huge time difference just because of the way I wrote the for loop. I normally don't use for..in loop for arrays but for some reason I used it while writing this function.

有人可以解释为什么这两种风格之间的性能存在巨大差异吗?

Can someone explain why there is this huge difference in performance between these 2 styles?

推荐答案

看看发生了什么不同的事情每次迭代:

Look at what's happening differently in each iteration:

for( var i = 0; i < p1.length; i++ ) 




  1. 检查 i< p1.length

  2. 增加一个

  1. Check if i < p1.length
  2. Increment i by one

非常简单快速。

现在看看每次迭代中发生的事情:

Now look at what's happening in each iteration for this:

for (var i in p1)


重复

Repeat


  1. 令P为obj的下一个属性的名称,其[[Enumerable]]属性为true。如果没有这样的属性,请返回(正常,V,
    为空)。


它必须在可枚举的对象中找到下一个属性。使用你的数组,你知道这可以通过一个简单的整数增量来实现,其中找到下一个可枚举的算法很可能不那么简单,因为它必须处理任意对象及其原型链键。

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.

这篇关于Javascript for..in vs for loop performance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆