【发布时间】:2020-09-24 22:00:47
【问题描述】:
我有以下结构:
const dictionary = [
{
words: ["foo", "bar"],
desc: "This is a description"
},
{
words: ["some", "word"],
desc: "This is another description"
}
]
我想访问给定单词的desc。例如:
getDescription(dictionary, "some") // "This is another description"
getDescription 的初始实现如下所示:
function getDescription(list, word) {
return list.find(item => item.words.includes(word)).desc
}
这是一种非常简单的方法,但我想知道是否可以将 list 转换为其他东西以提高效率(在速度方面),如果说 list 有 5000 个项目,其中 @987654329 @ 从 1 到 5 或 6 不等。
例如,这种初始转换会有帮助吗?:
list = list.reduce((acc, item) => ({
...acc,
...item.words.reduce((acc, word) => ({
...acc,
[word]: item.desc
}), {})
}), {}
)
}
它会重复很多描述,但访问将是即时的 (list["some"] // This is another description)。
这些问题都存在吗?我会感觉到任何性能的速度差异吗?优化,还是只是浪费时间?
【问题讨论】:
-
您的问题在我看来是使用浏览器内数据库的好地方:en.wikipedia.org/wiki/…。
标签: javascript arrays performance optimization reduce