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:
    1. 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.


    2. 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)


    BrowserinString.searchArray.indexOf
    IE6zero942859
    IE7zero125390
    Ff2zero201631
    Ff3zero713
    O9zero28147
    Safari3zero18831

    Search time in ms.

    Also popular now: