What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class:

class Box {
  constructor(x, y, width, height, frame, object_class, id) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.frame = frame;
    this.object_class = object_class;
    this.id = id;
  }

The purpose of frames_to_boxes is to efficiently look up Boxes by their frame number instead of looping through the entire array and comparing frames. However, I have noticed that checking if a specific element in frames_to_boxes is null is taking around 25ms according to my performance analysis, which seems unexpectedly slow.
I am measuring this using the following code snippet:

const t11 = performance.now();
if(this.frames_to_boxes[i] != null)
{
  const t12 = performance.now();

After logging the time difference (t12-t11), I am observing durations ranging from 5ms to 25ms. Interestingly, when accessing the array in groups of three (for example, checking indices 500, 501, 502), the first access typically takes 25ms while the subsequent accesses take only about 5ms each. It is worth mentioning that this.frames_to_boxes is a computed value in Vue. However, based on my investigations, I have confirmed that the code updating frames_to_boxes is not being repeatedly executed. It appears that the delay is arising from the array lookup itself.

Is it common for such operations to take 5-25ms? If not, what factors could be contributing to this slower performance? My measurements are based on Chrome browser.

Answer №1

When dealing with these types of operations, my preference is to utilize caching and hash tables in the form of JavaScript Objects. This approach allows for constant time complexity (O(1)) when checking for null values or accessing arrays of objects.

const myNewHashTable = {
  box1: [1,2,3],
  box2: [1,2,3],
  box3: '', 
  box4: []
}


if (myNewHashTable['box1']){
  console.log('found', myNewHashTable['box1'])
}
if (myNewHashTable['box3']){
  console.log('found',myNewHashTable['box3']) //this won't print
}
if (myNewHashTable['box4'].length > 0 ){
  console.log('found ','box4') //this won't print
}

Answer №2

After attempting to generate a simplified example without relying on Vue, I noticed that the problem disappeared entirely. This discovery suggested to me that even though frames_to_boxes isn't being recalculated, it seems that the Vue engine is actively monitoring for changes in dependencies or something along those lines.

By implementing Object.freeze on my Box elements prior to adding them to the primary array, I was able to resolve the issue at hand. Consequently, the process of checking for null now consumes less than 1ms, meeting expectations.

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

What is the best method for verifying that audio has not been loaded correctly?

After creating a script to scrape for mp3 audio file URLs and load them into my HTML audio element's src, I encountered an issue where some of the URLs were not functioning properly. As a result, the audio was unable to execute the load() method since ...

Having trouble loading JSON data in your ExtJS Tabpanel?

I have a tabpanel set up with two panels, and I am fetching data via JSON. The data retrieval works perfectly in the first tabpanel, but I'm facing issues parsing the JSON data in the second tabpanel. Any suggestions on how to approach this? var regi ...

A Comprehensive Guide on Implementing String Values in Highchart Series

When attempting to pass a string value (data) to the highchart series, I encountered an issue where it would display a blank chart. Is there a specific way to use a string value in the series of the highchart jQuery plugin? var data="{name: 'Jane&apo ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Exploring methods to trace the factory's property that is receiving updates from another factory within AngularJS

Hey there, I'm new to Angularjs and I have a bunch of factories in my application. The situation is, let's say we have obj1 in factoryA. Whenever I console.log(obj1), it displays numerous properties associated with it. This object is being update ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

The issue I'm facing is that the style loader is failing to load the CSS within the <head

I am currently facing an issue with importing my CSS into my webpack bundle for our Angular 1 application. Initially, everything was working fine as we bundled our application using Webpack. The HTML included the bundle and vendor scripts, additional Java ...

Vue component retrieval on the client side

I am attempting to retrieve a component using Vue with cdn in order to dynamically re-render from a public project that contains a file named cash-sale.vue with the .vue extension. <script> export default { data(){ return { "rows&quo ...

The URIError occurred while attempting to decode the parameter '/December%2015,%' within the express framework

After setting up a middleware using the express framework that handles a URI with a date as a parameter, I encountered a small issue. app.get("/:date",function(req,res){ var result; var myDate=req.params.date if(moment(myDate).isValid()) ...

Is there any npm module available that can generate user-friendly unique identifiers?

Struggling to come across a user-friendly and easily readable unique ID generator for storing orders in my backend system. I have considered using the timestamp method, but it seems too lengthy based on my research. ...

Avoiding Multiple Clicks on Anchor Tags in AngularJS

After implementing the sharing functionality, I have noticed that it works fine but there is a repeating issue with the user list. Every time the 'a' tag is clicked multiple times, the user list gets repeated. Can someone guide me on how to resol ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

Using arrays to create visual Google charts

I am attempting to pass an array of numbers to a Google chart by extracting the array from a div with the class .likescount. var i, $mvar = $('.likescount'); function logit( string ) { var text = document.createTextNode( string ); $(&a ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); ...

What is the method for checking the pathname condition?

Hello, I am attempting to create an if statement for the pathname, but I am having trouble getting it to work properly. if (pathname == "/") { category = 'home'; pagetype = 'homepage'; } If the pathname matches "/", the script ...

Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below, .then((response) => { return response.json(); }) .then((jsonRespo ...

[Error]: Unable to access the 'getCroppedCanvas' property as it is undefined in React Cropper

I am currently utilizing the "React Cropper" library (https://www.npmjs.com/package/react-cropper). I have included this code snippet (similar to many examples): import React from 'react'; import Cropper from 'react-cropper'; export ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Looking for an easy solution in RegExp - how to locate the keys?

Similar Inquiries: Retrieving query string values using JavaScript Utilizing URL parameters in Javascript I am tasked with extracting specific keys from a series of URLs where the key is denoted by 'KEY=123'. My goal is to identify and e ...