javascript - 检查数组中是否存在某些内容的最佳方法是什么?
问题描述
我正在创建的项目涉及对数组进行多次搜索,我意识到如果我不这样做,我可能会看到服务器性能问题的最佳方式。
我想知道在数组中查找值的服务器密集程度最低的方法是什么,我们将不胜感激。
我看到有些人在这个网站上回答这个问题,但答案不一,有些人说基本的 for 循环是最好的,其他人说 indexOf 和 findIndex 会表现更好,但不确定哪个最好,或者是否有不同的选择。
解决方案
Time complexity of searching in an array of length n
is O(n)
whereas using a Map will give you time complexity of O(1)
because you don't need to iterate over a Map
to know if particular element exists in it. You can get the element by using its key
.
If elements exists, it will be returned in O(1)
time, otherwise you will get undefined
meaning element you searched for doesn't exists in the Map
So its better to use Map
instead of an array in your case.
推荐阅读
- numpy - Pytorch:Numpy 数组
- python - 如何在 Tensorflow 的期望时期改变对损失施加的权重?
- typescript - ESlint 在类中给出关于索引器签名的错误
- unity3d - 在 Unity 中,尽管删除了脚本,但当我创建另一个同名文件时,它说脚本是重复的
- github - Github API - 比较 2 个提交 - 大比较 - 无法获取所有更改的文件
- javascript - Javascript让双重声明
- python - Numpy element-wise 通过矩阵 B 中的值对矩阵 A 的每个值取幂
- python - 从整个 DataFrame 的字符串中删除尾随 .0
- javascript - D3 可缩放的 Sunburst 和 React 通过道具更新
- c# - 如何录制两个音频输入和一个视频输入?