views:

56

answers:

1

I want to filter a table with an input box. It works but it is slow on smartphones which are my target platform - Iphone, Htc Touch HD (800 rows take about 4sec to filter).

Please let me know if you can help speed this up.

function time(){
    var now = new Date();
    var time = now.getTime();

    return time
}

function filter (phrase, _id){
    var starttime = time();
    var words = phrase.value.toLowerCase().split(" ");
    var table = document.getElementById(_id);
    var ele = null;
    var rows = new Array();
    for (var r=0 ; r < table.rows.length; r++){
        ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
        var displayStyle = 'none';
        for (var i=0 ; i < words.length; i++) {
            if (ele.toLowerCase().indexOf(words[i])!=-1){
                displayStyle = '';
            }else {
                displayStyle = 'none';
                break;
            }
        }
        rows[r] = displayStyle;
    }
    alert((time() - starttime)/1000 +" Sec");
    for(var k=0; k < rows.length; k++){
        table.rows[k].style.display = rows[k];
    }
}
+2  A: 

Sounds like the performance is somewhat reasonable, given the platform, but here are a few ideas:

1.) Don't calculate the length of your arrays during each for iteration (see https://developer.mozilla.org/en/A_re-introduction_to_JavaScript#Arrays )

2.) perform your toLowerCase() on the search string once at the beginning, not during each row checked

3.) the biggest hog is probably your use of innerHTML and replace(), but it's going to depend on the browser implementation, see if you can replace it with a more efficient method of getting the text from the cells you need to compare.

protobuf
+1 for the link (although you should make it a link), some good tips in it.
Andrew Coleson