简体   繁体   中英

Search a large array in Javascript more efficiently?

I am writing a script that allows organisation of records and data.

However a problem right now is I use an array to store a large amount of information and at a point in my script this array is searched for a matching id and updated. The data search begins to get quite slow when the array size is more than 200 elements.

Is there any way to more efficiently search the array?

I am currently using find.(function(a){return x == y};);

Each element in my array is also a tuple.

Sample code:

   onPipelineChanged: function(component, event, helper)
   {
    var titleid = event.getParam("titleid");
    var title = event.getParam("title");
    var maxSeats = event.getParam("maxSeats");
    var seatsInUse = event.getParam("seatsInUse");  
    var item = event.getParam("item"); //This is the item that was moved.
    var allGuestsList = component.get("v.allItems");

    //Searches guest list for matching guest of who got moved.
    var actualGuest = allGuestsList.find(function(moving){return moving.id == item.id;}); //***REALLY INEFFICIENT***

You can try a search algorithm like binary search. binary search

finding in array with length 200 can't be hard operation for any computer, even very old.

find or map or filter or while or for works fast. What may works slow - is if you are frequently changing html. so optimize DOM operations, try to calculate everything in memory and change html only once after all data is calculated etc

for example: a lot of manipulations with 100 000 length array took just 7-8 milliseconds (0.007 of sec)

 var timestart = new Date().getTime() var arr = Array.from({length: 100000}, Math.random) var newArr = arr .filter(_ => _ < 0.5) .map(_ => { return {val: _ * 2}}) .reverse() .join(',') .split(',') var timeend = new Date().getTime() console.log ('execution time (sec) ' + ((timeend - timestart) / 1000)) // for me 0.007 of sec 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM