lmdb-js icon indicating copy to clipboard operation
lmdb-js copied to clipboard

Incrementing integers

Open timotejroiko opened this issue 2 years ago • 2 comments

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!

timotejroiko avatar Jun 20 '23 16:06 timotejroiko

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.

kriszyp avatar Jun 21 '23 04:06 kriszyp

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

timotejroiko avatar Jun 21 '23 19:06 timotejroiko