Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case.

To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres.

I have come up with two methods to approach this:

  • Assign a boolean for each property of every object individually OR
  • Create an array containing the list of assigned properties for each object

Here are the options:

Option 1:

[{id: 1, name: 'some movie 1', comedy: true, thriller: true, drama: true, action: false, adventure: true},
{id: 2, name: 'some movie 2', comedy: false, thriller: true, drama: false, action: false, adventure: false},
{id: 3, name: 'some movie 3', comedy: true, thriller: true, drama: true, action: false, adventure: true},
{id: 4, name: 'some movie 4', comedy: true, thriller: true, drama: true, action: false, adventure: false}, ...]

Option 2:

[{id: 1, name: 'some movie 1', genre: ['comedy','thriller','drama']},
{id: 2, name: 'some movie 2', genre: ['thriller','drama']},
{id: 3, name: 'some movie 3', genre: ['comedy','thriller','adventure']},
{id: 4, name: 'some movie 4', genre: ['comedy','thriller']}, ...]

Personally, I prefer option 2 as it is more concise and does not store redundant data (false boolean values).

However, I am concerned about the performance implications. Using .include() to check arrays seems slower compared to a simple boolean check as seen in option 1.

This leads me to a dilemma between redundancy and performance. Is there a better solution that could address this issue like using a different data structure?

Thank you in advance!

Answer №1

When working with option 1, it's not necessary to explicitly define the false properties. Simply leave them as undefined, which is considered a falsy value.

const movies = [
  {id: 1, name: 'some movie 1', comedy: true, thriller: true, drama: true, adventure: true},
  {id: 2, name: 'some movie 2', thriller: true},
  {id: 3, name: 'some movie 3', comedy: true, thriller: true, drama: true, adventure: true},
  {id: 4, name: 'some movie 4', comedy: true, thriller: true, drama: true,}
];

const comedies = movies.filter(m => m.comedy);

console.log(comedies);

By following this approach, unnecessary data redundancy is eliminated without compromising filtering performance.

Answer №2

Instead of having multiple keys for genres, consider using a single key with an integer representing different genres as flags:

comedy  drama   something else  
   1      0            1       === 1 * 2^2 + 0 * 2^1 + 1 === 5

This way you can simplify your data structure like this:

{
    id:1,
    name: "some",
    genre: 5
}

To check if 'comedy' is included in the genres, you would do:

(genre ^ 4) === (genre - 4)

For checking 'drama', it would be:

(5 ^ 2) === (5 - 2) //false

You have the flexibility to use bitmasking genre & 4 as well, according to your preference.

Answer №3

It is not recommended to perform extensive data filtering on the client side. This can lead to slow computation of large datasets, causing the main browser thread to block and resulting in UI lag and slowdowns. The ideal approach is to establish a server with an API dedicated to handling such filtering tasks independently from the client. By querying the API, you can easily retrieve the filtered data without impacting client-side performance. If excessive data filtering on the client becomes a performance issue, it indicates a flaw in the app's structure.

If for some reason filtering must be done on the client side, utilizing a WebWorker is advised. This allows the filtering to occur in a background thread without affecting the UI responsiveness.

However, performing client-side filtering (with or without WebWorker) may encounter challenges across different browsers due to varying JavaScript implementations. Benchmarking different methods can help determine the most efficient approach. I conducted a benchmark test here which showcases differences in performance between Chrome, Firefox, and Safari.

https://i.stack.imgur.com/X1mLb.png

The results reveal that each browser, based on its JavaScript engine (V8, SpiderMonkey, Webkit), exhibits different speeds. For optimal performance across browsers, Array.includes() emerges as a reliable choice, displaying strong results in Chrome, decent performance in Firefox, and good performance in Safari.

Conclusion:

  1. Create an API for filtering tasks whenever possible
  2. If client-side filtering is necessary, utilize a WebWorker
  3. For best results, consider using Array.includes()

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

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...

The functionality of a radio button triggering a form submission to different pages is experiencing issues with Firefox

This piece of code is designed to submit a form when a radio button is clicked, and depending on which radio button is selected, the form action should change. While this code works fine in Chrome and Opera, it doesn't seem to function properly in Fir ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Error: Unable to split function. Attempting to retrieve API response via GET request using ngResource

I am trying to retrieve some data from an API using ngResource by utilizing the get method. Even though I have set up a factory for my resource, when implementing it in my controller, I encounter an error stating URL.split is not a function. I'm stru ...

Retrieve all elements within an Angular6 Directive that share the same name as the Directive

I have created a custom Directive called isSelected and applied it to several elements in different components as shown below: <i isSelected class="icon"></i> <i isSelected class="icon"></i> <i isSelected class="icon"></i ...

What is the process behind Twitter's ability to quickly show my profile?

Scenario I was intrigued by the different loading times of Twitter's profile page based on how it is accessed: Clicking the profile link in the menu results in a 4-second load time with DOM and latest tweets loade ...

Attempting to include a new choice on a drop-down menu and ensure its visibility within the drop-down menu

On my journey into the world of web development, I am facing a challenge with adding an option to a dropdown list. Despite pressing the add button to insert "Pasta" as a new option, it is not showing up in the list immediately. However, selecting all optio ...

The HTML select element fails to drop down over the THREE.js scene

I'm currently working on enhancing the Three.js editor for a project. editor link One of the tasks I'm tackling is adding a select element on top of the viewport in the editor. Unfortunately, the dropdown functionality of the select element isn ...

knockout, loop within a loop

Imagine I have a group of Humans who own Cats, and those Cats have Kittens class Person { String name; Cat[] cats; } class Cat { String name; Kitten[] kittens; } class Kitten { String name; } Now I want to display all my Kittens with ...

Is it acceptable to designate the db instance as a global variable so that it is always accessible without requiring the "require" statement in Node.js?

I am just starting my journey with "node js" and I am currently working on a program that requires a database model similar to "wpdb" in WordPress. Should I create it as a global variable or use the "require" statement only when needed? Your help in provi ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

Full replacement of a cell within an HTML table

I have a scenario like the following: <table id="myTable"> <tr> <td class="1">cell 1</td> <td class="2">cell 2</td> </tr> <tr> <td class="3">cell 3</td> &l ...

jQuery AJAX calls are unsuccessful, while NodeJS requests are running smoothly

I am experiencing an issue with a RESTful web service that returns JSON. Interestingly, a NodeJS command line test application is able to retrieve the JSON data without any problems: Successful NodeJS Application: var request = require("request"); var bt ...

Does a browser's cache utilize storage for XMLHttpRequest responses?

I have a question regarding browsers in general, with a focus on Chrome. Imagine I have the following code snippet in my file, index.html: <img src='//path/to/foo.img'></img> The file foo.img changes on my server every hour. I woul ...

Encountering the error message "String length is invalid" during the execution of ng build for a library

While working with Angular and attempting to build a large library using the command ng build <project>, we encountered the following issue: ❌ Generating "fesm2015" Invalid string length The build for fesm2020 was successful, but the sourcem ...

The Handlebars template remains blank, failing to show any data or error messages

//////////////////////////////////// // Function to append items // ////////////////////////////////// function addItems(data) { var template = document.getElementById('items').innerHTML; var handlebarsTemplate = Handlebars.compile(tem ...

Using Typescript in combination with snowpack may result in nullish coalescing operators being generated when targeting a version lower than ES2020

I've been working on compiling my TypeScript code/packages to ensure compatibility with Safari Version less than 14. After researching, I discovered that nullish coalescing operators (??) are not allowed in the targeted version. Despite changing my t ...

Ways to identify whether a day is in Pacific Standard Time (PST) or Pacific Daylight

While working on setting a date in node js for my server located in IST, I am trying to figure out whether the date would fall under PDT or PST time (depending on Daylight Saving Time being on or off). If my server was in PST/PDT time zone, this decision ...