【发布时间】:2020-04-03 12:42:17
【问题描述】:
我有两个数组,一个包含来自 CSV 文件的 200.000 个产品对象,另一个包含来自数据库的 200.000 个产品对象。
两个数组都包含具有相同字段的对象,但有一个例外:数据库对象也具有唯一 ID。
我需要将所有 200.000 个 CSV 对象与 200.000 个数据库对象进行比较。如果 CSV 对象已存在于数据库对象数组中,我将其与匹配的 ID 一起放入“更新”数组中,如果不存在,则将其放入“新”数组中。
完成后,我更新数据库中的所有“更新”对象,并插入所有“新”对象。这很快(几秒钟)。
然而,比较步骤需要几个小时。我需要比较三个值:通道(字符串)、日期(日期)和时间(字符串)。如果三个都相同,那就是匹配。如果其中一个不是,那么它就不匹配。
这是我的代码:
const newProducts = [];
const updateProducts = [];
csvProducts.forEach((csvProduct) => {
// check if there is a match
const match = dbProducts.find((dbProduct) => {
return dbProduct.channel === csvProduct.channel && moment(dbProduct.date).isSame(moment(csvProduct.date), 'day') && dbProduct.start_time === csvProduct.start_time;
});
if (match) {
// we found a match, add it to updateProducts array
updateProducts.push({
id: match.id,
...csvProduct
});
// remove the match from the dbProducts array to speed things up
_.pull(dbProducts, match);
} else {
// no match, it's a new product
newProducts.push(csvProduct);
}
});
我正在使用 lodash 和 moment.js 库。
瓶颈在于检查是否有匹配,关于如何加快速度的任何想法?
【问题讨论】:
标签: arrays node.js performance compare