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

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Are you looking to work with an ASMX web service and navigate JSON utilizing JavaScript or

Currently, I am using asmx to fetch data from a database. public class TestPage1 { public int UserID { get; set; } public string UserName { get; set; } public string Password { get; set; } public string FirstName { get; set; } public ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Developing unique custom methods in Django REST API for generic views

As an intern, I am currently working on a project that involves developing a DRF API to interact with a mobile app built by my colleague using the Ionic framework. Our task is to create new users, and here is the method in my view: class NewUser(generics. ...

Encountered an error with symbol '@' while utilizing ES6 decorators

I have recently set up a React project and now I'm attempting to integrate MobX into it. This requires using decorators such as: @observable However, when I try to implement this, I encounter the following error: https://github.com/mobxjs/mobx Mod ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

"Could you please help me understand the process of receiving a JSON in an Express

When working with React, I encountered an issue where the JSON data sent to me from the front-end is in a strange format (an object with the data as a string). I am unsure how to convert it back into the object type. This is what I send: const data = { ...

Modifying the key values of an associative array

In my code snippet, I am attempting to loop through a JSON array and update the values within it. Here is an overview of what the JSON structure looks like: <?php $json='[{"type":"dropdown","label":"Is the property tenanted ?","req":0,"choices":[{ ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...

How can I trigger the offcanvas opening in Bootstrap 5 through code?

I am having an issue with a bottom offcanvas on my webpage. I want to open it when a card is clicked, but despite trying to set the necessary attributes and using code from the documentation, it only shows the backdrop briefly before immediately dismissing ...

The issue persists where Chrome WebAPI's chrome.webRequest.onBeforeSendHeaders is failing to modify the parameters in the outbound requests

I have been attempting to include an IP address in the X-Forwarded-For parameter within the requestHeader, but my code does not seem to be working based on the examples provided in the Chrome API. Below is the code snippet I am currently using: var reque ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Vue plugins that emit events

In the scenario where I have a basic Vue plugin that does not contain any components, but simply provides some methods to the user: export default { install(Vue, options) { // Unrelated tasks go here. } Vue.prototype.$foo = () => { ...

Unable to transfer a function to a component using <Route /> tag

In the Erm component, the function setErm is undefined even though it is received by the App component. When passing something like something='foo', the ERM component receives it but not setErm={props.setErm} const App = props => { console. ...

Utilize GSON library to translate JSON into a MAP object

Is there a better way to convert JSON response to a Map using GSON library? I attempted the following code but I am only able to retrieve the ArrayList value. Map<String, Object> map = gson.fromJson(response, HashMap.class); ArrayList responseOption ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...