Search in an array (set) in JavaScript
Recently solved the problem when it was necessary to determine whether a certain (string) value falls into the set of valid values.
In JavaScript 1.6, there is an indexOf method of an Array object to search in an array, but this method is not supported in Internet Explorer. For IE, this method is implemented by looping through an array.
But since the order of the elements was not important and every millisecond was counting, I compared the performance of loop enumeration in an array with other search options (without enumeration).
And the search options without searching are as follows:
To evaluate the performance of each of the three search methods, I created a test page on which 100,000 lines of the form "StringN" are created, where N is the line number, and then the string "String60000" is searched.
It turned out that the in operator works almost instantly (the runtime is always 0), even in IE6!
Search time in ms.
In JavaScript 1.6, there is an indexOf method of an Array object to search in an array, but this method is not supported in Internet Explorer. For IE, this method is implemented by looping through an array.
But since the order of the elements was not important and every millisecond was counting, I compared the performance of loop enumeration in an array with other search options (without enumeration).
And the search options without searching are as follows:
- Gluing an array into a string and search in a string
if (myarray.join().search("Строка поиска") != -1) { ... }
* This source code was highlighted with Source Code Highlighter.
When using this method, it is necessary to take into account the uniqueness of the occurrence of the search substring in the string glued from the array. To do this, you can, for example, use gluing characters that a priori do not appear on the line:if (("#" + myarray.join("#,#") + "#").search("#Строка поиска#") != -1) { ... }
* This source code was highlighted with Source Code Highlighter. - Using an object instead of an array, “hash keys” are hash keys
if ("Строка поиска" in myarray) { ... }
* This source code was highlighted with Source Code Highlighter.
To evaluate the performance of each of the three search methods, I created a test page on which 100,000 lines of the form "StringN" are created, where N is the line number, and then the string "String60000" is searched.
It turned out that the in operator works almost instantly (the runtime is always 0), even in IE6!
Test Results (Celeron 2.4)
| Browser | in | String.search | Array.indexOf |
|---|---|---|---|
| IE6 | zero | 94 | 2859 |
| IE7 | zero | 125 | 390 |
| Ff2 | zero | 2016 | 31 |
| Ff3 | zero | 71 | 3 |
| O9 | zero | 281 | 47 |
| Safari3 | zero | 188 | 31 |
Search time in ms.