To search for an element in an arbitrary vector, we need to traverse the vector elements one by one. In a vector of N elements, this means that on average you will have to do N / 2 tests to find the element of the vector, which can be quite if the vector is large.
On the other hand, the Javascript map is implemented using a hash table , which is a data structure specially designed for element to be fast. Generally, the number of operations required is constant or logarithmic in the number of elements, rather than being directly proportional.
An interesting exercise is to make a chart showing the times of the two versions for different numbers of elements.
As for the vector, this data structure is optimized for fast access to an element, given an index. If you already know the index of an element, you can access it directly using vetor[i]
, without having to do an indexOf.
Finally, if your vector is sorted with elements in ascending order, you can do a binary search , while instead of linear sweep, which is much faster. It's the difference between looking up a telephone number in an alphabetically organized phone book and doing the same search in a whole jumbled list.