javascript - 为什么在 js 中运行两个单独的循环与运行单个 for 循环之间存在性能差异

标签 javascript performance for-loop

我在我的服务器上运行了这段代码,我注意到运行两个单独的循环与单个 for 循环之间存在性能差异,有人可以解释为什么吗?

for(let k=0;k<100000000;k++) {
    let s = Date.now();
    for(let i=0;i<1e9;i++) { i + 100 }
    for(let i=0;i<1e9;i++) { i + 100 }
    let s1 = Date.now() - s;

    s = Date.now();
    for(let i=0;i<2e9;i++) { i + 100 }
    let s2 = Date.now() - s;

    console.log(s1, s2 , s1 - s2)
}

这些是我的 json 结果:https://pastebin.com/bRqku0zJ

最佳答案

我也在 dev2 中发布了这个问题。感谢da-tihttps://dev.to/dati/comment/eii1

This has nothing to do with JIT compiler, loops, multi-threading or BigInt. If this was a some quiz question it would test: -Understating that every number in js implicitly is floating point number -Knowing how floating point addition works and that (unlike addition of integers) it takes multiple hw level operations

Addition_and_subtraction

To make this test fair for both one loop variant and two loops variant:

 s = Date.now() 
 for(let i=0;i<1e10;i++) { i + 100 } 
 for(let i=1e10;i<2e10;i++) { i + 100 } 
 console.log(Date.now() - s)

 s = Date.now() for(let i=0;i<2e10;i++) { i + 100 }
 console.log(Date.now() - s)

Now both variants work with exact same numbers and perform exact same floating point operations (time diff is consistently <20ms on my machine now, where it was 500-1500ms before)

TLDR: floating point

关于javascript - 为什么在 js 中运行两个单独的循环与运行单个 for 循环之间存在性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711752/

相关文章:

php - Javascript Fancybox 2 关闭按钮/链接事件不起作用

javascript - 删除嵌套在对象内部的数组项

javascript - 当页面上存在透明 PNG 时,站点上的所有 Javascript 在 Firefox 4 中执行得非常慢

java - 如何重构在字符串列表中搜索文本的 for 循环

r - 如何使嵌套 for 循环更高效并与 apply 一起使用

javascript - 如果父元素有子元素则添加 onclick 类

c# - 高性能 C# 服务器套接字的技巧/技巧

java - java中的早期冲洗

mysql - 加入不同服务器上的数据库时的 Rails 性能

python - 在 for 循环中创建多个 tkinter 小部件并将它们分配给变量