How to combine this text faster?

I create autosuggest for names. When a user enters text in a text field, he gets to the server and starts it:

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 do it faster? I am using Node.js

+6
source share
4 answers

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

Executing this logical client side will greatly improve performance.

+7
source

Most likely you should use filter , on the one hand, because it is 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; 
+1
source

If you store names in sorted order, you can use binary search to find the namespace in sorted order starting with the name fragment that the user has typed so far, instead of checking all the names one by one.

In a system with a rather strange programming language, where I wanted to find all matches containing what the user had typed so far in any position, I got a satisfactory result for a small implementation effort, reviving http://en.wikipedia.org/wiki / Key_Word_in_Context . (Once at university, I looked for the KWIC physical index, printed using an IBM linear printer, and then linked as a document for that purpose only.

+1
source

I would suggest you do this on the client side and prefer (for now) the while loop instead of the filter / forEach approach:

 var names = [ /* list of 1000 names */ ] , query = 'alex' , i = names.length , matched_names = []; while(i--){ if(names[i].indexOf(query) > -1){ matched_names.push(names[i]); } } return matched_names; 

This will be much faster (even if the / forEach filter is supported mostly). See This Test: http://jsperf.com/function-loops/4

+1
source

Source: https://habr.com/ru/post/896054/


All Articles