javascript - 这个for循环会迭代多次吗?

标签 javascript performance

我一直在和同事讨论一些代码:

for(const a of arr) {
  if(a.thing)
    continue;
  // do a thing
}

一个建议是过滤它并使用 forEach

arr.filter(a => !a.thing)
  .forEach(a => /* do a thing */);

有一个关于重复不必要的讨论。我查过这个,我找不到任何东西。我也试图弄清楚如何查看优化后的输出,但我也不知道该怎么做。

我希望 filterforEach 变成非常类似于 for ofcontinue< 的代码,但我不知道如何确定。

我怎样才能知道?到目前为止,我唯一尝试过的是谷歌。

最佳答案

您的第一个示例(for in 循环)是 O(n),它将执行 n 次(n 是数组的大小)。

你的第二个例子(forEach 的过滤器)是 O(n+m),它将在过滤器中执行 n 次(n 是数组的大小),然后执行 m 次(m 是结果数组的大小)过滤发生后)。

因此,第一个示例更快。但是,在这种没有非常大的样本集的示例中,差异可能以微秒或纳秒为单位进行测量。

关于编译优化,本质上就是所有内存访问优化。主要的解释器和引擎都会分析代码中与函数、变量和属性访问相关的问题,例如访问图的频率和形状;然后,利用所有这些信息,优化它们的隐藏结构以提高访问效率。就循环替换或流程分析而言,基本上没有对代码进行优化,因为大部分代码都是在运行时优化的(如果代码的特定部分确实开始花费过长的时间,它可能优化了代码)。

When first executing the JavaScript code, V8 leverages full-codegen which directly translates the parsed JavaScript into machine code without any transformation. This allows it to start executing machine code very fast. Note that V8 does not use intermediate bytecode representation this way removing the need for an interpreter.

When your code has run for some time, the profiler thread has gathered enough data to tell which method should be optimized.

Next, Crankshaft optimizations begin in another thread. It translates the JavaScript abstract syntax tree to a high-level static single-assignment (SSA) representation called Hydrogen and tries to optimize that Hydrogen graph. Most optimizations are done at this level.
-https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e

*虽然continue可能会导致执行进入下一次迭代,但它仍然算作循环的一次迭代

关于javascript - 这个for循环会迭代多次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990895/

相关文章:

bash - 如何使这个 bash 素数生成器更快 [SPOJ]

java - 为什么 Java ArrayList 删除功能似乎花费这么少?

java - 在 1.6 VM 上运行的 "-target 1.5"生成的 Java 类文件的性能影响?

javascript - 如何根据 Knockout js 模型设置控件样式

具有相同字段的javascript数组组

javascript - 从数组中提取最大的数字

performance - 制作内连接 linq 或使用 [table].[joiningTable].column 是一样的吗?

r - 在 R 中对大型、非常稀疏的二元矩阵进行聚类

javascript - 改变一个 y 轴的范围 nvd3/d3

javascript - 如何在鼠标悬停时以动态高度提供圆 Angular 图像