0

I'm working on an online dictionary that has to be executed completely client-side and can't use any external libraries, so I'm loading the dictionary entries as a series of JavaScript arrays and then passing them to the webpage. I use a search function that iterates through an index of each entry and checks it for matches against a search string, then returns all matching entries. (This is actually done by hiding non-matching entries with CSS to avoid having to re-draw up to 30,000 entries in HTML with each search.)

elen = Entries.length;
for (j=0;j<elen;j++) {
    shh_cypher = ShoshoniIndex[j]; //These search indexes are created from the JS array by an earlier function
    eng_cypher = EnglishIndex[j];

    //displays results and hides all other dictionary entries
    if(shh_cypher.match(search_term)) {
        document.getElementsByTagName("dt")[j].style.display = "";
    }
    else if(eng_cypher.match(search_term)) {
        document.getElementsByTagName("dt")[j].style.display = "";
    }
    else document.getElementsByTagName("dt")[j].style.display = "none";

    document.title = "Search is " + Math.round((j/elen)*100) + "% complete…";
}

There's a small delay on the search in Chrome, Opera, and Safari, but it's acceptable. In IE and Firefox it takes a really long time to return any results for the first search, and then works great (almost no delay) for any subsequent searches, but the initial delay makes it unusable. With a shortened version of the database, everything works fine across the board, so I know it's just a matter of timing, and not that it doesn't work in those browsers.

Any ideas on how to whip through a 30,000-entry array faster in JavaScript, or ideas about why Firefox and IE would be causing problems, but not the others?

Here's the page: http://goo.gl/btBYOd (It takes a few seconds to load fully, and in IE you'll have to allow the JavaScript.)

gwistix
  • 60
  • 1
  • 6
  • Both htatche's and Richard's ideas seem to have helped, but it's still slower than I'm comfortable with. Why does indexOf() work faster than match()? – gwistix Feb 22 '14 at 23:02

2 Answers2

1

Maybe by caching your DOM elements, instead of going through the DOM in every iteration, this would be faster.

var dt_elements = document.getElementsByTagName("dt");
...
dt_elements[j].style.display = "";
htatche
  • 693
  • 3
  • 17
1

In addition to htatche's comment on how you should avoid going through the DOM every iteration, if all you're doing is searching through a bunch of strings to find the presence of a substring, using indexOf() is probably better practice and may offer superior performance to match().1

Community
  • 1
  • 1
Richard Ye
  • 685
  • 4
  • 12