在 Node.js 中并行使用 lodash 或下划线每个方法 运行 吗?

Does lodash or underscore each method run in parallel in Node.js?

我知道在 node 中所有东西都是并行运行的,除了你的代码。阅读 here and here.

我正在寻找一个可能的场景,我在内存中有一个非常大的数组,我想对它的每个元素执行一个小的计算。此计算的执行顺序并不重要。

在节点中,由于事件循环,所有 I/O 的执行非常高效,但是当您遍历集合时,不涉及 I/O 并且如果此迭代花费的时间太长,您可以阻止所有传入那段时间的要求。

这个gist contains a nonBlockingForEach that Neilk wrote in his article Why you should use Node.js for CPU-bound tasks让我想知道我是否写了这样的东西

var my_very_large_array = [...];
my_very_large_array.forEach(function() { ... })
//or
_.each(my_very_large_array, function() { ... })

我会在我的服务器上遇到性能瓶颈(这个库回退到本机 forEach,如果存在的话)

据我所知,有很多像 async.js 这样的库可以做到这一点,但我总是在浏览器中使用 lodash 或下划线来完成这些任务。

我也试过 bluebird.js 但 promisify 这些方法没有按预期工作。

所以我的问题是这样的。当您使用 forEach 方法遍历大型集合时,lodash 或下划线是否会成为 node.js 环境中的性能杀手?

"Performance Killer" 是一个相对的、相当有分量的术语。

要回答您的直接问题,请在 lodash 中 forEach 或并行下划线 运行:否。它使用标准的同步迭代。

有一个名为“Web Workers”的新标准,它允许后台工作在同一进程的单独线程中发生。这需要更高版本的 node.js,以及从此处安装的单独软件包:

来自wiki page

The W3C and WHATWG envision web workers as long-running scripts that are not interrupted by user-interface scripts (scripts that respond to clicks or other user interactions). Keeping such workers from being interrupted by user activities should allow Web pages to remain responsive at the same time as they are running long tasks in the background.

The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.

您可以通过安装 webworker-threads 软件包

在 node.js 中启用网络工作者

So my question is this. Is lodash or underscore a performance killer in a node.js environment when you iterate through a large collection using a forEach method?

是的,在处理大量数据时,lodashunderscore 都会在典型的 node.js 设置中降低性能,因为它们会阻塞唯一可用的线程,使得在事件循环中排队的其他任务受到影响。但是,如果您要 运行 在网络工作线程中执行这些操作,那么您的主线程将可以自由地继续正常处理工作。

NodeJS 是一个单线程单进程应用程序。无论您是在单个 forEach 中处理整个数组,还是将其分成由事件队列处理的多个循环,都没有关系。 CPU 核心仍然需要相同数量的工作。

如果你想利用多核。您需要使用 cluster 模块,并创建多个处理数组不同部分的进程。

NodeJS 中没有共享内存或线程锁定。因此,您必须将数组拆分成多个部分,以便每个进程继续工作。

https://nodejs.org/api/cluster.html