Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match this text faster?

I'm building an autosuggest for names. When the user types in the textbox, it hits the server and runs this:

var names = [ list of 1000 names ]; //I have a list of 1000 names, this is static.
var query = 'alex';
var matched_names = [];

//This is when it gets slow....
names.forEach(function(name){
    if(name.indexOf(query) >= 0){
        matched_names.push(name);
    }
});

return matched_names;

How can I make this faster? I'm using Node.js

like image 832
user847495 Avatar asked Aug 27 '11 22:08

user847495


2 Answers

If the names are static then move this code to the client and run it there. The only reason to run code like this on the server is if the data source is dynamic in some way.

Doing this logic client-side will dramatically improve performance.

like image 150
Andrew Hare Avatar answered Sep 19 '22 10:09

Andrew Hare


You should probably use filter instead, for one thing, because it's native:

var names = [ /* list of 1000 names */ ];
var query = 'alex';
var matched_names = names.filter(function(name) {
    return name.indexOf(query) > -1;
});
return matched_names;
like image 32
Ry- Avatar answered Sep 19 '22 10:09

Ry-