javascript - difference between async array.map() and async npm package
问题描述
[Context]
I had a loop here, that I will have 760000 interations, so I'm trying to optimize it.
[Question]
In my loop, i'm using a async array.map()
function
cells.map(async (cell) => {
if (cell[0] === '!') continue;
[...]//so much code here
return someObj;
}
I saw the async package but I don't know what is faster, an "async map" function or the "async" package?
Please, if you can, explain the way one is faster then other.
解决方案
异步代码
你听说过承诺吗?如果您认为您的映射将花费太长时间并且您想要执行不需要该数组结果的以下代码,即独立代码,那么您可以使用promise 包装它以更改执行流程。
const heavyMapping = arr => Promise.resolve(
arr.map(cell => {
if (cell[0] === '!') continue;
[...]//so much code here
return someObj;
})
);
//Call the function.
heavyMapping(arr).then((result) => processResult(result));
//Rest of your program
foo();
bar();
所以执行将是这样的:heavyMapping -> foo -> bar ... -> processResult
. 如果您在没有异步代码的情况下运行代码,它将是heavyMapping -> ... -> processResult -> foo -> bar
. 请注意,如果您使用的是异步代码,这并不意味着您的代码将并行执行,因为这是并发编程和并行性,这是并发的一种特殊情况,您有足够的硬件来同时执行这两个任务. 阅读更多相关信息:https ://medium.com/@deepshig/concurrency-vs-parallelism-4a99abe9efb8 。无论如何,如果您不想阻止执行foo
并且bar
您可以使用承诺或aync/await
面对这个问题。
地图
我建议您在这种特殊情况下使用forEach
而不是使用和链接。为什么?让我解释一下:map
filter
map
Map
当您想要转换原始数据以获取新数组中的结果时,使用方法。例如,假设您有一个名为people
包含具有以下格式的对象的数组:{name: 'X', lastName: 'Y', age: 23 }
并且您想要将name
and的串联lastName
作为fullName
属性,那么您可以使用map
如下people.map(person => { fullName: `${name} ${lastName}` });
:- 另一方面,假设您要筛选年龄至少为 18 岁的人的数据。您可以
filter
为此使用:people.filter(person => person.age > 18);
.
在您的特定情况下,您可以使用以下链接的方法:
arr
.filter(cell => cell[0] === '!')
.map(/*so much code here*/);
请注意,如果您的代码块(这里有这么多代码)与数据转换无关,我鼓励您使用forEach
chained tofilter
而不是map
.
抱歉,如果我不理解您的问题,但这就是我对此的解释。快乐编码。
PS:如果你不知道`${expression}`
,它被称为模板字符串。
推荐阅读
- raspberry-pi - 使用 Gstreamer 播放 RTSP 流时出现问题
- google-cloud-platform - 组和 IAM 角色
- aws-lambda - 在 Dynamodb Python 查询中捕获异常
- php - 找到 2 到 4 个单词,它们之间最多有 2 个逗号
- java - 如何更正我的代码以删除 CORS 获取问题?
- openshift - Openshift:如何增加 sti-build 的内存限制
- python - 如何将用户输入与excel数据框匹配
- python - 如何在 bcp 命令中指定长度前缀?
- python - Django - 使用表单发布到特定的 URL
- c++ - 字符串迭代器永远不会到达 std::string::end()