Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is sorting with Table.orderBy() more efficient or not? #1778

Closed
rayzhao99 opened this issue Aug 4, 2023 · 2 comments
Closed

Is sorting with Table.orderBy() more efficient or not? #1778

rayzhao99 opened this issue Aug 4, 2023 · 2 comments

Comments

@rayzhao99
Copy link

rayzhao99 commented Aug 4, 2023

When integrating the caches and optimistic updates into our codes, we now need to load & sort one entire table, and don't know which implementation is more efficient. So, could you please give any advices on this?

Background:

  1. the records defined with a primary key of id, which is a simple string uuid,
  2. the number of the records is up to about thousands, at most tens of thousands,

Objective: load all the records in a particular table, and sort the loaded by id in ascending.

The code snippet is as below.

// #1. load & sort with `Table.orderBy()`
liveQuery(() => db.table1.orderBy('id').toArray());

// #2. load the records, and sort separately
liveQuery(() => db.table1.toArray()).subscribe(
    records => records.sort((r1, r2) => r1.id === r2.id ? 0 : (r1.id < r2.id) ? -1 : 1)
);

Our current codes are implemented as the second, since we think it would release the underlying transaction sooner. However,

  1. is our consideration meaningful, even without caches and optimistic updates? The best way should do a performance test, and we will do it later. Could you please give any analysis or suggestions?
  2. With the caches now, we guest the first implementation might outperform for loading, as well as for reloading after CRUDs, since the records are already sorted by PK and cached. Is our guess meaningful or correct, from your opinion?

Thanks!

@dfahlander
Copy link
Collaborator

db.table1.toArray() will always return a result sorted by the primary key. Basically, it's the same as doing db.table1.orderBy('id').toArray() - so the first one isn't optimized more than the second one. And when using caches and optimistic updates (the default in latest dexie@4), this contract remains the same.

So my advice is to keep doing the orderBy() query (or just a toArray()) and skip the manual sorting part.

@rayzhao99
Copy link
Author

Got it. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants