如何更有效地做到这一点? [英] How to do it more efficiently?

查看:101
本文介绍了如何更有效地做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下,我们应该得到一些数据...

Let's imagine we should get some data...

var data = [];

//some code omitted that might fill in the data (though might not)

然后,我们需要做的对数据进行处理。我的问题是如何更有效地做到这一点。 像这样:

if (data.length) {
    for (var i = 0; i < data.length; i++) {
        //iterate over the data and do something to it
    }
}

或只是像这样:

for (var i = 0; i < data.length; i++) {
    //iterate over the data and do something to it
}

问题的关键是,是否迭代与否之前检查长度是多少?

The point is whether to check the length before iterating or not?

推荐答案

我不认为这是值得检查是否执行根据<$ c中的循环数据$ C>长度 ,因为它可能没有太大的差别性能明智的,如果在循环仅执行几次。

I don't think it's worth checking whether to execute the for loop based on the length of data as it probably won't make much difference performance-wise if the for loop is only executed a few times.

但通常会更快拿到长度第一,而不是把它作为 I&LT; data.length ,因为它需要每次访问变量。作为其中的方法是最有效的,通过数据循环,不同的浏览器针对不同类型的环路的优化。然而,这只有IE浏览器是的认真的,所以我认为优化其他浏览器慢(数量级比在下面的测试中其他浏览器慢订单)可能不值得的。

But generally it is faster to get the length first rather than putting it as i<data.length as it'll need to access the variable each time. As for which way is the most efficient to loop through data, different browsers are optimized for different kinds of loops. However, it's only IE which is seriously slow (orders of magnitude slower than other browsers in the below tests) so I think optimizing for other browsers may not be worth it.

下面是以下基准结果(以+最快的表示,并表示最慢用 - ):

Here's the results for the following benchmarks (the fastest indicated by + and slowest indicated by -):


           FF      Chrome  Safari  Opera   IE6      IE7      IE8 
Method 1  +0.163+  0.221   0.246   0.269  -11.608- -12.214- -7.657-
Method 2   0.175  +0.133+  0.176  +0.147+   8.474    8.752   3.267
Method 3   0.206   0.235   0.276   0.245    8.002    8.539   3.651
Method 4   0.198   0.372   0.447   0.390   +6.562+  +7.020+  2.920
Method 5   0.206   0.372   0.445  -0.400-   6.626    7.096  +2.905+
Method 6   0.176   0.167  +0.175+  0.223    7.029    8.085   3.167
Method 7  -0.263- -0.567- -0.449-  0.413    6.925    7.431   3.242

方法1:使用标准循环:

for (var i=0; i<data.length; i++) {
    var x = data[i]
}

方法2:是标准循环,分配长度所以不必每次访问

Method 2: Using "standard" for loops, assigning length so it doesn't have to access each time:

for (var i=0, len=data.length; i<len; i++) {
    var x = data[i]
}

方法3:这是类似jQuery使用在 $方法每()。请注意,分配给 LEN ,这样它没有获得长度每次。

Method 3: This is similar to the method jQuery uses in $.each(). Note the assigning to len so that it doesn't have to get the length every time.

for (var x=data[0], len=data.length, i=0; i<len; x=data[++i]) {}

方法4:,而循环,持续向前。 警告:需要在阵列中的每个项目进行评估,以<​​code>真正,即不 0 未定义等等!

Method 4: Using while loops, going forwards. WARNING: needs each item in the array to evaluate to true, i.e. not false, 0, null, undefined, '' etc!

var x, i=0
while (x = data[i++]) {}

方法5:同为4的方法,只能用做相同的:

Method 5: The same as method 4, only using for to do the same:

for (var x,i=0; x=data[i++];) {}

方法6:通过循环循环使用向后,而

Method 6: Looping through the loop backwards using while:

var i = data.length
while (i--) {
    var x = data[i]
}

方法7:使用方法4 /法5,但不需要的物品,以评价真正,将 X =数据[我++] :

Method 7: Using method 4/method 5, but without needing items to evaluate to true, replacing x = data[i++]:

var x, i=0, len=data.length
while ((x=data[i++]) || i<len) {}

这首先检查数据[我++] 是否计算为真正然后检查它是否是最后一个项目,以便它可以在IE浏览器类似的表现用较少的问题,等的阵列。请注意,当使用,而 VS 在这种情况下,没有一个明显的区别,但我preFER ,而,因为我觉得它更清楚了。

This first checks whether data[i++] evaluates to true then checks whether it's the last item so it can have similar performance in IE with fewer problems with null and false etc in the arrays. Note that when using while vs for in this case there wasn't a noticeable difference, but I prefer while as I think it's more clear.

我一般不喜欢优化,除非有特定的长时间运行的任务,因为它常常是在可读性成本 - 请只有做到这一点,如果你有,你已经有了大量的数据到一个特定的情况下,负载等: - )

I generally don't like to optimize unless there's a specific long-running task as it often comes at a cost of readability - please only do it if you've got a specific case where you've got lots of data to load etc :-)

编辑:因为方法4/5是如此之快于IE浏览器,增加了一个版本副作用较少

Because methods 4/5 were so fast on IE, added a version with fewer side effects.

编辑2:重新编制所有的测试,这一次没有任何浏览器扩展,并在一段较长的时间。这里的code为完整起见(抱歉让这个帖子这么久:)

EDIT 2: Redid all of the tests, this time without any browser extensions and over a longer period of time. Here's the code for the sake of completeness (sorry for making this post so long:)

function Tmr() {
    this.tStart = new Date()
}

Tmr.prototype = {
    Time: function() {
        var tDate = new Date()
        var tDiff = tDate.getTime() - this.tStart.getTime()
        var tDiff = tDiff / 1000.0 // Convert to seconds
        return tDiff
    }
}

function normalfor(data) {
    for (var i=0; i<data.length; i++) {
        var x = data[i]
    }
}

function fasterfor(data) {
    for (var i=0, len=data.length; i<len; i++) {
        var x = data[i]
    }
}

function jqueryfor(data) {
    for (var x=data[0], len=data.length, i=0; i<len; x=data[++i]) {

    }
}

function whileloop(data) {
    var x, i=0
    while (x = data[i++]) {

    }
}

function fixedwhileloop(data) {
    var x, i=0, len=data.length
    while ((x=data[i++]) || i<len) {

    }
}

function forwhileloop(data) {
    for (var x,i=0; x=data[i++];) {

    }
}

function fixedforwhileloop(data) {
    for (var x,i=0,len=data.length; (x=data[i++])||i<len; ) {

    }
}

function whilebackwards(data) {
    var i = data.length
    while (i--) {
        var x = data[i]
    }
}

var undefined
var NUMTIMES = 1000000
var data = '$blah blah blah blah blah|'.split('')

function test() {}
function getfntime(fn) {
    // Get the rough time required when executing one of the above functions
    // to make sure the `for` loop and function call overhead in `run` doesn't 
    // impact the benchmarks as much
    var t = new Tmr()
    for (var xx=0; xx<NUMTIMES; xx++) {
        fn()
    }
    return t.Time()
}
var fntime = getfntime(test)

function run(fn, i){
    var t = new Tmr()
    for (var xx=0; xx<NUMTIMES; xx++) {
        fn(data)
    }
    alert(i+' '+(t.Time()-fntime))
}

setTimeout('run(normalfor, "1:normalfor")', 0)
setTimeout('run(fasterfor, "2:fasterfor")', 0)
setTimeout('run(jqueryfor, "3:jqueryfor")', 0)
setTimeout('run(whileloop, "4:whileloop")', 0)
setTimeout('run(forwhileloop, "5:forwhileloop")', 0)
setTimeout('run(whilebackwards, "6:whilebackwards")', 0)
setTimeout('run(fixedwhileloop, "7:fixedwhileloop")', 0)
//setTimeout('run(fixedforwhileloop, "8:fixedforwhileloop")', 0)

这篇关于如何更有效地做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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