首页 > 解决方案 > 检查数组中是否存在某些内容的最佳方法是什么?

问题描述

我正在创建的项目涉及对数组进行多次搜索,我意识到如果我不这样做,我可能会看到服务器性能问题的最佳方式。

我想知道在数组中查找值的服务器密集程度最低的方法是什么,我们将不胜感激。

我看到有些人在这个网站上回答这个问题,但答案不一,有些人说基本的 for 循环是最好的,其他人说 indexOf 和 findIndex 会表现更好,但不确定哪个最好,或者是否有不同的选择。

标签: javascript

解决方案


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.


推荐阅读