DEV Community

roverbober
roverbober

Posted on

IndexedDB: Understanding Performance Pitfalls (Part 1)

The main issue we’re addressing here is the long initialization time of IndexedDB.

When you initiate a connection to a database, the code typically looks like this:

window.indexedDB.open("TestDB", 1);

Normally, this process is quite fast, taking around 20 milliseconds — a pretty swift operation. However, during the first-time setup, it might take a bit longer because it involves creating the database from scratch.

Feel free to try it out for yourself. Go to the sandbox and take a look at the “Initialization Time” value.

Image description

After refreshing the page a few times, you’ll see that this value typically remains low.

At the moment, IndexedDB is empty. It consists of 30 tables, but there’s no data in them. You can verify this by opening DevTools and checking the tables and their contents.

Image description

Let’s change this by adding some data. Simply click the “Add Items” button, and the script will start populating the tables.

Image description

Please wait until it’s finished. This will increase the overall size of IndexedDB to 379 Mb.

Image description

After refreshing the page, you may notice a slightly higher “Initialization Time” value — nothing to be too concerned about at this stage.

However, try closing the tab and reopening it; this time, you might experience a noticeable delay, potentially up to 2 seconds. Keep in mind that the exact duration can vary depending on your device and browser. My tests were conducted on a Mac using Chrome.

If you continue to add more data, this delay will become even longer.

Making your users wait for a few seconds when they open your web application is not ideal. To address this issue, consider these tips:

  1. Don’t block your UI rendering while waiting for IndexedDB. Opening a connection is an asynchronous operation, so load and display what you can to your users, and wait for data from IndexedDB in the background. Once it’s available, render the data.
  2. Review what you store in IndexedDB. If you’re storing files or media, think about using a Service Worker and Cache API. This approach can simplify the database structure, reduce its size, and enhance its performance.
  3. Consider splitting your database into multiple databases. For instance, if your application can be used by multiple users on the same device, create a separate database for each user. With a single database containing 800 megabytes of data, initialization time may be around 3 seconds. However, by dividing it into two databases, the initialization time can be reduced to 1.5 seconds.

Top comments (0)