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

Incrementing integers #244

Open
timotejroiko opened this issue Jun 20, 2023 · 2 comments
Open

Incrementing integers #244

timotejroiko opened this issue Jun 20, 2023 · 2 comments

Comments

@timotejroiko
Copy link

Hello,

I would like to inquiry on the best ways to increment an integer, is there any way more efficient than this?

db.transaction(() => {
    let int = db.get(key);
    db.put(key, int + 1);
});

The above method has a pretty large performance penalty for such a simple operation.

If there isn't any better way, I would like to inquire about adding methods for efficient incrementation of numerical values.

Thanks!

@kriszyp
Copy link
Owner

kriszyp commented Jun 21, 2023

Most of the time, you can do this more efficiently by using optimistic writes. If you set your store to use versions, you can do this, which will only increment the integer if it hasn't changed (otherwise it will try again), guaranteeing atomic incrementation:

  let success;
  do {
    let { value, version } = db.getEntry(key);
    success = await db.ifVersion(key, version, () => db.put(key, int + 1, version + 1);
  } while(!success);

It is possible that this can be result in multiple iterations inhighly write contention situations, but usually this is a good technique (if it rarely retries). And it may be nice to provide a low-level incrementation, but generally these primitives work well across a pretty broad range of scenarios.

@timotejroiko
Copy link
Author

Thank you for the suggestion, unfortunately the transaction method still seems to be faster in my benchmarks, but i will look more into it!

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