dumbmatter / fakeIndexedDB

A pure JS in-memory implementation of the IndexedDB API
Apache License 2.0
564 stars 69 forks source link

Poor insertion performance when using multiEntry #44

Open nolanlawson opened 4 years ago

nolanlawson commented 4 years ago

Hi, thank you so much for making fakeIndexedDB! I love using it in my tests; it's a marvelous piece of software. :slightly_smiling_face:

I'm running into an issue where fakeIndexedDB is taking a very long time to insert data. Here is a test where I am inserting 1000 objects, each with 100 multiEntry keys.

On my Dell XPS 13 (i7 processor) running Ubuntu 20.04 and Node v12.16.3, this takes 35.5 seconds to complete. Unfortunately this means that my tests time out, and it's not feasible for me to create/destroy the database between each test.

In contrast, this same code takes 595ms in Chrome, 774ms in Firefox, and 1773ms in GNOME Web (WebKit, like Safari).

Looking at a Node cpuprofile, it appears that the main issue is that FDBTransaction._start queues up many recursive calls (if you insert 10,000 objects it will throw a stack overflow error), and each of those are spending time in Index.storeRecord and RecordStore.add. (Maybe switching to a non-recursive pattern would help?)

Screenshot from 2020-06-04 07-55-24

Attached is the trace file, which you can load into Chrome Dev Tools in the "JavaScript Profiler" section. If you'd like to profile this yourself, you can run node --inspect-brk index.js, then in chrome:inspect open the Node debugger, then in Profiler click "start".

CPU-20200604T075535.cpuprofile.gz

dumbmatter commented 4 years ago

I think the problem is that each object store and index is just an array. That makes inserting and deleting objects very slow. Also it's pretty slow for retrieving and updating objects. You know, it's almost as if there are reasons real databases use less stupid data structures :)

Multi entry indexes with a lot of keys, that's gonna be a problem.

For a long time I've wanted to address this, but never got around to it. I'm not sure when I will, although I probably should soon cause I've used many of your libraries and learned a lot from your code. No promises though :)

If you or anyone else feels like taking a stab at it, I think it should be possible to do by just editing https://github.com/dumbmatter/fakeIndexedDB/blob/0fd26fe2c91eecee58a2d48e48cf60ea93c2e9e7/src/lib/RecordStore.ts - replace the stupid array implementation with a B-tree or whatever.