user94663
user94663

Reputation:

How can I improve the speed of my table filtering JavaScript on smartphones?

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];
    }
}

Upvotes: 2

Views: 231

Answers (2)

Niels Bom
Niels Bom

Reputation: 9397

Profile your JavaScript, using the Firebug profiler for instance. Then you can see which operations take the longest. Measuring is knowing.

Upvotes: 0

protobuf
protobuf

Reputation: 604

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.

Upvotes: 2

Related Questions