Home > database >  Sort array of 50 000 objects - Javascript
Sort array of 50 000 objects - Javascript

Time:10-05

I need to sort an array of objects in javascript(angular project).

My object is fairly simple, just a single layer of some strings and ints:

{
    id: 7683,
    base: "example",
    value: 1000000,
    poster: "example",
    price: 100,
    itemCount: 49
}

There are going to be 50 000 of these objects, and I'm displaying them in a table, where the user should be able to sort by any of the properties (I'm paginating them to save resources during rendering).

My current implementation is the base javascript sort alg with a custom sort func:

this.myList.sort((a,b) => a.id - b.id)

Currently this takes around 25 seconds, which is not the user experience I'm after. I tested a datatable implementation, which seemed to work quickly, so I'm trying to find out why mine is not as fast.

What is the fastest way to accomplish my sort? Do I need to write a custom quick sort? If so, do you mind explaining what about the default sort with a custom function makes it slower than something I might write myself? Thanks

CodePudding user response:

I recommend to you using mat-sort its very fast.

Another things you can do to improve sorting:

  1. If you can - sorting by server is way more faster and easier.
  2. Check how long it takes to the API request to fully get the data - "25 seconds" may cause by slow network / file format (like string that need to be parsed / gzip and more)... and not the sort itself.
  3. Render the data only after the data is already sorted (like sorting in rxjs pipe / *ngIf...).
  4. You can use trackBy it can speed the process by a little.
  5. You can save the data of the first paginator page in localStorage - then in the second time you can render to the user the first page (from localStorage) - while you sorting "behind the curtain" and rerendering the full data.
  6. There is a few more solution it depend on the app you've got - for example if its a small app with related data - you can sort the data during app initialization APP_INITIALIZER
  7. Angular material table/paginator/sort can speed up the ordering a lot - this link example is examine 23,575 objects.

CodePudding user response:

try some solution like quicksort Algorithm: https://github.com/duereg/js-algorithms/blob/master/lib/algorithms/11-sorting/quickSort.js

  • Related