Optimizing JS Array Search

Posted by The.Anti.9 on Stack Overflow See other posts from Stack Overflow or by The.Anti.9
Published on 2010-03-19T04:03:33Z Indexed on 2010/03/19 4:11 UTC
Read the original article Hit count: 175

Filed under:
|

I am working on a Browser-based media player which is written almost entirely in HTML 5 and JavaScript. The backend is written in PHP but it has one function which is to fill the playlist on the initial load. And the rest is all JS. There is a search bar that refines the playlist. I want it to refine as the person is typing, like most media players do. The only problem with this is that it is very slow and laggy as there are about 1000 songs in the whole program and there is likely to be more as time goes on.

The original playlist load is an ajax call to a PHP page that returns the results as JSON. Each item has 4 attirbutes:

  1. artist
  2. album
  3. file
  4. url

I then loop through each object and add it to an array called playlist. At the end of the looping a copy of playlist is created, backup. This is so that I can refine the playlist variable when people refine their search, but still repopulated it from backup without making another server request.

The method refine() is called when the user types a key into the searchbox. It flushes playlist and searches through each property (not including url) of each object in the backup array for a match in the string. If there is a match in any of the properties, it appends the information to a table that displays the playlist, and adds it to the object to playlist for access by the actual player.

Code for the refine() method:

function refine() {
    $('#loadinggif').show();
    $('#library').html("<table id='libtable'><tr><th>Artist</th><th>Album</th><th>File</th><th>&nbsp;</th></tr></table>");
    playlist = [];
    for (var j = 0; j < backup.length; j++) {
        var sfile = new String(backup[j].file);
        var salbum = new String(backup[j].album);
        var sartist = new String(backup[j].artist);
        if (sfile.toLowerCase().search($('#search').val().toLowerCase()) !== -1 || salbum.toLowerCase().search($('#search').val().toLowerCase()) !== -1 || sartist.toLowerCase().search($('#search').val().toLowerCase()) !== -1) {
            playlist.push(backup[j]);
            num = playlist.length-1;
            $("<tr></tr>").html("<td>" + num + "</td><td>" + sartist + "</td><td>" + salbum + "</td><td>" + sfile + "</td><td><a href='#' onclick='setplay(" + num +");'>Play</a></td>").appendTo('#libtable');
        }
    }
    $('#loadinggif').hide();
}

As I said before, for the first couple of letters typed, this is very slow and laggy. I am looking for ways to refine this to make it much faster and more smooth.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about optimization