admin管理员组

文章数量:1336186

I went throught speed up your javascript.

So i did this personal speed test:

    var count = 50000000;
    var testDummy;

    // test 1
    testDummy = 0;
    var test1Start = new Date().getTime();
    var i;
    for (i=0;i<count;i++) {
        testDummy++;
    }
    var test1End = new Date().getTime();
    var test1Total = (test1End-test1Start);

    // test 2
    testDummy = 0;
    var test2Start = new Date().getTime();
    var i
    for (i=count; i--;) {
        testDummy++;
    }
    var test2End = new Date().getTime();
    var test2Total = (test2End-test2Start);


    debug(
      "test1\n" + 
      "total: " + test1Total + "\n" + 
      "test2\n" + 
      "total: " + test2Total 
    );

I get not significant results, like sometimes they are even and sometimes not.

My question is, if i use for loop like this: "for(i=count;i--;)" is it really faster ? Am i doing something wrong in my tests.

Thanks for your help!

I went throught http://www.youtube./watch?v=mHtdZgou0qU speed up your javascript.

So i did this personal speed test:

    var count = 50000000;
    var testDummy;

    // test 1
    testDummy = 0;
    var test1Start = new Date().getTime();
    var i;
    for (i=0;i<count;i++) {
        testDummy++;
    }
    var test1End = new Date().getTime();
    var test1Total = (test1End-test1Start);

    // test 2
    testDummy = 0;
    var test2Start = new Date().getTime();
    var i
    for (i=count; i--;) {
        testDummy++;
    }
    var test2End = new Date().getTime();
    var test2Total = (test2End-test2Start);


    debug(
      "test1\n" + 
      "total: " + test1Total + "\n" + 
      "test2\n" + 
      "total: " + test2Total 
    );

I get not significant results, like sometimes they are even and sometimes not.

My question is, if i use for loop like this: "for(i=count;i--;)" is it really faster ? Am i doing something wrong in my tests.

Thanks for your help!

Share asked Feb 4, 2011 at 21:31 developerGuiledeveloperGuile 5272 gold badges11 silver badges20 bronze badges 5
  • I think you got something wrong here, for(i=count;i--;) doesn't make any sense... – MarioVW Commented Feb 4, 2011 at 21:35
  • Sorry, it does make sense (when it reaches 0 casts to false)... however I don't see how this could be faster – MarioVW Commented Feb 4, 2011 at 21:36
  • 1 I suppose the idea is that instead of executing two statements per loop iteration (test, increment) you can bine the increment step into the test step and execute only one statement per iteration... – maerics Commented Feb 4, 2011 at 21:39
  • The 3rd arguments is absent so the usual operation time is skipped, and the 2nd argument is faster since there is not operator paraison. I mean that usually if you do as a 2nd arg, i<length, then it pares i with length, then it pares the result with false to stop the for loop. In this case there is only one paraison with false, if 'i' is 0 then it is automatically false. – developerGuile Commented Feb 4, 2011 at 21:46
  • 1 As I mentioned in my answer, you may be more likely to get that optimization using predecrement instead of postdecrement. – Dan Breslau Commented Feb 4, 2011 at 21:55
Add a ment  | 

4 Answers 4

Reset to default 4

(I'd write this as a ment, but it'd be too long.)

First: Worrying about the efficiency of a for loop is almost always a waste of (your own) time. What's inside of the loop usually has much more impact on performance than the details of how the loop is specified.

Second: What browser(s) did you test with? Different browsers will show different performance profiles; even different versions of the same browser will differ.

Third: It's not out of the question that the JavaScript engine optimized your loops out of the picture. A JavaScript piler could simply look at the loop and decide to set testDummy to 50000000 and be done with it.

Fourth: If you really want to split hairs on performance, I'd try for(i=count; --i != 0;) as well as for(i=count;i--;). The former may save a machine instruction or two, because executing the subtraction (in the predecrement step) may automatically set a hardware flag indicating that the result was 0. That flag is potentially wasted when you're using the postdecrement operator, because it wouldn't be examined until the start of the next iteration. (The chances that you'd be able to notice the difference are slim to none.)

Well...

for( i=0 ; i < len ; i++ )

is practically the same as

for( i = len ; i-- ; )

Lets describe it:

case 1: let i be 0
boolean expression
let i be i + 1

case 2: let i be len
let i be i - 1
cast i to boolean (type coersion) and interpret it.

The difference should be minute and depends entirely on how efficient type coersion is pared to a normal boolean expression.

Incidentally, test this:]

var i = count;
while( i-- ) {}

There's nothing wrong with your tests.

The blocks that you are testing are very-near identical, meaning the difference in execution speeds are going to be trivial. In both examples, a variable (i) is set to a fixed value and looped until it reaches a fixed value (count). The only thing that differs is i++ and i--, which in terms of speed, I think are practically the same.

The thing you have to be careful of (not do) is calculate the "loop until" value inside the loop definition.

I have made some tests too, here are the results.

In many articles, books authors propose that "optimized" loops are faster.

It seems that modern browsers have some optimizations for "normal" loops.

Firefox 13.0.1

  • Normal Loop: 0.887
  • Opt1: 1.025
  • Opt2: 1.098
  • Opt3: 1.399

Chrome 19.0.1

  • Normal Loop: 3.349
  • Opt1: 3.12
  • Opt2: 3.109
  • Opt3: 3.095

IE8

  • Over 12sec...
  • Repeatedly crashed during tests.

<script type="text/javascript">

function p(p) { console.log(p); }
// function p(p) { document.write(p); }

var testFn = function(num, niz, fn) {
    var start = new Date().getTime();

    fn(num, niz);

    var result = (new Date().getTime() - start) / 1000;

    return result;
}

function normalLoop(num, niz) {
    for (var i = 0; i < niz.length; i++) {
        niz[i] = 'a' + i;
    }
}

function opt1(num, niz) {
    var len = niz.length;
    for (var i = 0; i < len; i++) {
        niz[i] = 'a' + i;
    }
}

function opt2(num, niz) {
    for (var i = niz.length; i--;) {
        niz[i] = 'a' + i;
    }
}

function opt3(num, niz) {
    while(i--) {
        niz[i] = 'a' + i;
    }
}

var niz = [];

var num = 10000000;

for (var i = 0; i < num; i++) { niz.push(i); };

p('Normal Loop: ' + testFn(num, niz, normalLoop));
p('Opt1: ' + testFn(num, niz, opt1));
p('Opt2: ' + testFn(num, niz, opt2));
p('Opt3: ' + testFn(num, niz, opt3));

</script>

本文标签: For loop speed performance in javascriptStack Overflow