Comparison of performance between serializing an object to indexedDB and using JSON.stringify

I am curious about the efficiency differences in terms of browser/CPU/memory between using JSON.stringify for serialization versus writing an object to an object store in indexedDB.

The context for this question is optimizing the process of writing an object from a database to a client's hard drive. Typically, the object is retrieved with a 'get' statement and then saved as a string using JSON.stringify before being written to disk. Upon retrieval, the string is converted back to an object using JSON.parse and stored in the database. This seemingly involves unnecessary steps of unserialization and reserialization.

My first question is whether it is possible to directly retrieve the serialized form of an object from the database, eliminating the need for stringify/parse operations when saving and retrieving data.

The second part of my inquiry focuses on using indexedDB without indexing or querying by value. In such cases, storing the stringified object instead of the object itself might offer advantages in reducing intermediary steps during read/write processes.

In scenarios where only out-of-line unique keys are used, avoiding stringify/parse could streamline disk operations, although modifying the data would require temporary conversion to an object format.

Comparing JSON functions to indexedDB serialization, I am intrigued by the potential performance differences. While non-object storage may seem more efficient, handling updates could pose challenges if objects need frequent conversions.

I aim to conduct experiments to observe any distinctions, yet I seek insights into the underlying mechanisms behind these two serialization methods.

EDIT

I recently learned about the structured clone algorithm used in indexedDB but wonder if further serialization occurs before storage. Additionally, JSON operates differently while not duplicating objects. These nuances have raised questions regarding the necessity of explicit serialization steps in databases.

After delving deeper into this topic, I realize that some aspects may be beyond my current understanding, leading me to reconsider whether my original inquiries hold significance.

Thank you.

EXAMPLE:

@Sam152 Incidentally, have you noticed any performance variations between using stringify versus direct object insertion in your database transactions? Please see the code snippet below for reference.

// var o = A large object.
var d;
write.x = 0;
write.y=[];

DB_open().then( inter );

function inter() { d = setInterval( write, 1000 ); }

function write()
  {
    let T = DB_open.base.transaction( [ 'os_name' ], 'readwrite' ),
        q = T.objectStore( 'os_name' ),
        start = Date.now();  

    T.oncomplete = function() { write.y.push( Date.now() - start ); }

    if ( write.x < 50 )
      write.x = write.x + 1;
    else
      {
        clearInterval(d);
        console.log( 'done' );
      };

    o.key = write.x;
    q.put( o );

    // OR

    q.put( { 'key' : write.x, 'd' : JSON.stringify( o ) } ); 

  } // close write

  // When complete.

  total = 0;
  write.y.forEach( ( v ) => { total = total + v; } );

Or, multiple put statements within the same transaction.

function write()

  {
    let T = DB_open.base.transaction( [ 'os_name' ], 'readwrite' ),
        q = T.objectStore( 'os_name' ),
        start = Date.now(),
        i;  

    T.oncomplete = function() 
      { console.log( 'Completed : ' + ( Date.now() - start ) ); }

    for ( i = 1; i < 51; i++ )
      {
        o.key = i;
        q.put( o );

        // OR

        q.put( { 'key' : i, 'd' : JSON.stringify( o ) } ); 
      };
  } // close write

Answer №1

Storing objects as strings in a database does not provide any performance benefits. Using JSON.stringify to convert an object to a string only adds unnecessary steps. It is advised against attempting to outsmart the indexedDB implementation in C++ by storing strings directly.

The serialization process in indexedDB occurs in C++, not JavaScript. Operations performed in JavaScript are typically much slower compared to those in C++.

In indexedDB, a string cannot be stored as an object due to its nature as a function-object. Objects that extend from Object without extending from Function are serializable, making them suitable for storage in indexedDB.

Methods attached to objects make them unserializable. The structured clone algorithm, now known as the serialization algorithm, handles the conversion of objects between JavaScript and C++ within indexedDB.

IndexedDB's serialization in C++ optimizes the byte format representation rather than simply converting to a string or object. Efficiently storing bytes involves complexities beyond just serialization performance.

C++ implementations handle the complexities of serialization, abstracting it away from developers. Converting values to strings in JavaScript can slow down program execution, so it's best to let indexedDB manage this process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

Switch between displaying the HTML login and register forms by clicking a button

Currently, I am working on a website that requires users to either log in or register if they do not have an account. Below is the code I have developed for the login page: <span href="#" class="button" id="toggle-login">Log in</span> <di ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

The failure of the ajax call to encapsulate is likely due to issues with object visibility

Having some trouble with a piece of code meant to run smoothly on Firefox 3.6. The issue arises when the variable this.xmlhttp, defined in STEP2 and used in STEP3, seems to be operating in different variable environments. Even though I expect the two usa ...

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

personalizing jquery templates

Currently, I am utilizing a jQuery template to showcase specific values. Within this template, I have included an if statement to determine if the age is considered old or not, with the result altering the background color accordingly. Previously, the co ...

Add a fresh record only if it contains information and there are no existing duplicates present

Is it possible to create a note with both a title and text, under certain conditions? The title must not be empty The title cannot already exist in the system When attempting to check for duplicates within my array, the boolean value always returns true ...

Is there a bug in the iOS platform code causing an unusual problem with valueForKeyPath:@"@max.totalSteps"?

I have been troubleshooting this issue for a few hours, and decided to seek expert advice or clues. Here is the problematic code snippet: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"plot" ofType:@"json"]; NSDictionary *dict = [NSDictiona ...

What is the best way for Protractor to effectively wait for a popover to be displayed and verify that it does not contain an empty string?

Whenever you hover over it, this appears - my popup: This is what the html looks like before we add the popover to the DOM: <span tariff-popover="popover.car2go.airport" class="ng-isolate-scope"> <span ng-transclude=""> ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

An issue occurred with player.markers not being recognized as a function when trying to utilize videojs markers

I am trying to add markers to my videojs player timeline. I have successfully implemented this feature a few months ago in a different project, but now when I try to use it again, I am encountering errors in the console and unable to see the markers on the ...

Python: generate JSON representation from a class and then unwrap it, Issue AttributeError: type object '' does not have a 'decode' attribute

So, I've been working on a Flask app and have a class that I reuse across multiple pages. To make things easier, I wanted to save the created class object in a pickle file and then unpack it when needed. Unfortunately, every time I try to do this, I r ...