Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options.

Within the database, there is a table containing approximately 2000 rows detailing the final products along with their respective prices. Each row includes product ID, code, price, size, option, and color.

For example:

product_id / code / price / size / option / color

     1       ABC     20$     1       3        5
     2       DEF     30$     2       4        5
     3       FFF     30$     3       4        5

This system functions through AJAX calls, allowing for dynamic price updates based on selected options. Each time an option is changed, a query is made to the database to retrieve the corresponding product and display its price.

In this particular scenario, would it be advisable to fetch the entire list of products initially (as a single query with around 2000 rows), store it as a JavaScript object, and then filter it as needed?

Just to note, I am utilizing MySQL for this project.

Answer №1

Possibly yes, although there are numerous factors that could impact the outcome. It is assumed that:

  • The visitor is a typical web user
  • The ajax request takes approximately 100ms for a round trip

Under these conditions, it is highly likely that an average visitor's browser could browse through millions of products within that time frame.

However, if you are aiming to optimize user experience (i.e. reducing the delay caused by ajax), a hybrid approach is recommended:

Utilize caching extensively

Chances are that your product catalog undergoes minimal changes compared to the frequency of user access; resulting in a high volume of read operations. This presents an opportunity to circumvent direct database queries by caching something like

example.com/products/14/all-options.json
as a static file.

Storing text is cost-effective, whereas server CPU usage is more resource-intensive.

In scenarios where a specific product has numerous options (e.g. tens of thousands), an alternative approach could involve caching these options as a hierarchy of static files. For instance,

example.com/products/14/size-1/all-options.json
could contain all options for product #14 of size #1. Similarly,
example.com/products/14/size-1/option-4/all.json
would encompass all options for size 1, option #4, and so forth.

By filtering these smaller datasets using Javascript, you can effectively handle millions of products without necessitating extensive database queries or large downloads during initialization.

Answer №2

When dealing with 2000 objects in JavaScript and filtering, there may not be an issue. However, it's important to remember that MySQL is specifically designed for querying databases, making it a better option. Additionally, consider the limitations of mobile devices with low specifications, as well as PCs with limited resources. If the number of objects exceeds 2000, it could result in longer request times and filtering processes when using JavaScript.

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

Node.js and Socket.IO: Managing responses

In a unique scenario, the web page is initially served using HTTP. When the submit button is clicked, data is sent to the server and multiple web services are executed, which may take some time. The challenge is to quickly display the response page and the ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...

Tracking accurate responses with button click

In my quiz, I want to keep track of the correct answers selected by the player. When a player clicks on the correct answer, the counter should increase by one. At the end of the quiz, the HTML should display a message like "You got" + correct + "answers co ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

I used the `MyWindow=window.open` function to display a pop-up window and then navig

On my webpage (http://localhost:8088/hse/public/explorer), I have implemented two buttons: When these buttons are clicked, a new pop-up window will open at (http://localhost:8088/hse/public/explorer/1) onClick="MyWindow=window.open('http://local ...

Obtain an additional Element within the JSON Path

I'm attempting to conform to library limitations and am in need of defining a JSON Path that retrieves the subsequent object within a list, based on the index of a particular value. Consider the following scenario: {[ x, details of x, ...

Guide on sending files through an API request with formData() using Vuejs and Axios

My goal is to utilize an API to upload a file to the server. The documentation on documenter.getpostman outlines how to use the API: --form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/U ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Accessing the Key Name of a JSON Array in Android Using Dynamic Methods

I have a unique json url, which upon opening displays the following data { "Response": "Successful", "All_Items": [{ "Category": "1", "TotalCount": "5", "ExpiringToday": 2 }], "TopOne": [{ "id": "10", "ThumbnailPath": "http://exampleo ...

Exploring the depths of a multidimensional dictionary within AngularJS

I am currently working on a project using AngularJS. The data I have is in the form of JSON: { "leagues":{ "aLeague":{ "country":"aCountry", "matchs":{ "aUniqueID1":{ "date":"2014-09-07 13:00:00", "guest_play ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

The method by which npmjs.com evaluates the quality of code

After we release a package on npm, it provides us with insights such as popularity, quality, and maintenance on the search page (Refer to the example image below). I am particularly curious about how npm determines the quality metric. Any insights would be ...

Inconsistency found in Ajax DataTable data updates

Incorporating a DataTable ajax feature, I pass values to the controller. Here is a simplified version of the code: $(function() { $("#tableDiv").hide(); $("#submitDateFilters").on("click", function() { displayData(); $("#tableDiv").show(); ...

How can jQuery identify the elements that the selected text spans across?

In the midst of a project, I find myself in need of extracting specific text within an iframe. This text may traverse across multiple spans within the iframe, each identified by a unique ID spanning from 1 to the end of the page. My goal is not to retrie ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

Incorporating the Acts_as_votable gem alongside Angularjs for interactive voting functionality

I'm trying to figure out how to implement Acts_as_Votable in an Angular template for a car voting system. Despite my efforts, I can't seem to display the vote count when rendering the list in Angular. I think I may need to establish some kind of ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...