简体   繁体   English

+ =,++,+之间的性能差异

[英]Performance difference between +=, ++, +

我创建了这个测试http://jsperf.com/loop-counter为什么这三个表达式之间存在这样的差异。

because your test is wrong. 因为你的测试是错误的。 you're reusing the same variable, so the larger it gets, the slower it is to increment. 你重复使用相同的变量,所以它越大,增量就越慢。 take a look at this: http://jsperf.com/loop-counter/6 看看这个: http//jsperf.com/loop-counter/6

this is how jsperf works - preparation code is run only once, before all tests. 这就是jsperf的工作原理 - 在所有测试之前,准备代码只运行一次。

I tried running all three tests several times, and each time I reload the page, the first test I try is the fastest by far. 我尝试多次运行所有三个测试,每次重新加载页面时,我尝试的第一个测试是迄今为止最快的。

So I'm guessing there is some issue with the test being too short, ie the code that runs the tests is taking up most of the time. 所以我猜测测试有一些问题太短,即运行测试的代码占用了大部分时间。

如果这不是一个修辞问题而你实际上想要一个aswer:那么人们如何在浏览器中编写JS引擎。

It's because of what the program is doing behind the scenes: 这是因为该计划在幕后所做的事情:

l_count += 1; l_count + = 1; This adds the number 1 to the variable. 这会将数字1添加到变量中。

l_count = l_count + 1; l_count = l_count + 1; This calls the variable l_count, reads it, adds 1 to the result, and passes that back to l_count. 这将调用变量l_count,读取它,将结果加1,然后将其传递回l_count。

l_count++; L_COUNT ++; This adds 1 to the variable after the line is run. 在运行该行后,它会向变量添加1。 So the value is stored in another temporary variable while the line is done, then the value is returned, added 1 and saved back to the original value. 因此,当行完成时,该值存储在另一个临时变量中,然后返回该值,添加1并保存回原始值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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