简体   繁体   中英

Why is it faster to perform an assignment than do nothing?

  class Obj { constructor() { this.propA = ~~(Math.random() * 255 + 0.5); this.propB = ~~(Math.random() * 300 + 0.5); } } const arr1 = new Array(100000); for (var i = 0; i < 100000; i ++) { arr1[i] = new Obj(); } function test1() { let start = new Date(); for (var times = 0; times < 1000; times ++) { let n = 0; for (var i = 0; i < 100000; i++) { if (arr1[i].propA > arr1[i].propB) { n += 1; //arr1[i].propB = arr1[i].propA; //<-- try uncomment it } } } console.log(new Date() - start + 'ms'); } test1(); 

paste this code to developer tools(or a new .html file).

on my computer(win7 x64, chrome 63) it prints 1200-1600ms.

however when I uncomment the code it prints only 500-700ms.

I don't know why it happens...

I don't know why it happens...

Because after firs time when

arr1[i].propB = arr1[i].propA;

has been executed, from the next iteration

if (arr1[i].propA > arr1[i].propB)

will be false and hence that line n += 1; will not get executed.

Since you are saving one operations by replacing increment and assignment with only assignment , you see a improvement in speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM