JavaScript runs a function multiple times at various intervals

While tackling the well-known Ransom Note task, especially from a platform like HackerRank, I delved into experimenting with the execution time of a JavaScript function. My focus shifted slightly from the original task as I explored how the function performed when iterating through arrays of varying lengths.

I meticulously recorded the time it took to iterate through pairs of arrays with the following lengths: 1. 1000 elements 2. 10,000 elements 3. 100,000 elements 4. 200,000 elements 5. 400,000 elements

Naturally, I anticipated that the time taken would increase proportionally with the array's length and was curious to discern any underlying patterns.

To my surprise, the results revealed significant discrepancies in the execution time despite utilizing the same function on identical arrays under similar conditions. At times...

I documented the execution times for each array length within an object, resulting in the following data:

veryVeryBigData: {
  '1000':  [ 1, 0, 0, 0, 0, 1, 0, 0 ],
  '10000': [ 12, 12, 12, 12, 12, 12, 12, 12 ],
  '100000': [ 1464, 5498, 5637, 5591, 5389, 5524, 5481, 5440 ],
  '200000': [ 5858, 21847, 22704, 22214, 21638, 21845, 21798, 21926 ],
  '400000': [ 64027, 91809, 92233, 90515, 92953, 92394, 93374, 104708 ]
}

The data clearly illustrates substantial variations in execution times for certain iterations involving arrays of 100,000 elements or more.

If anyone could shed light on why this occurs or provide insights into further research areas for better comprehension, it would be greatly appreciated.

Below is the code snippet I utilized:

const ten = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
const thousand = Array(100).fill(ten).flat();
const tenThousand = Array(10).fill(thousand).flat();
const hundredThousand = Array(10).fill(tenThousand).flat();
const twoHundredThousand = Array(2).fill(hundredThousand).flat();
const fourHundredThousand = Array(4).fill(hundredThousand).flat();

const wordsArrays = [thousand, tenThousand, hundredThousand, twoHundredThousand, fourHundredThousand];

const veryVeryBigData = { 1000: [], 10000: [], 100000: [], 200000: [], 400000: [] };

const checkMagazine = (mag, note) => {
  const start = Date.now();
  let iterations = 0;
  let result = "Yes";
  let magazine = [...mag];

  note.map((w, i) => {
    iterations++;
    const index = magazine.indexOf(w);
    if (magazine.includes(w)) {
      magazine.splice(index, 1);
    } else {
      result = "No";
    }
  });

  const totalTime = Date.now() - start;
  veryVeryBigData[note.length].push(totalTime);

  console.log("Result: ", result);
};

const performChecks = (mags, ns) => {
  mags.map(magazine => {
    ns.map(note => {
      if (note.length === magazine.length) {
        checkMagazine(magazine, note);
      }
    });
  });
};

//for experimental purposes, compare two identical arrays to solely calculate iteration time
//perform 8 comparisons to observe diverging results

for (let i = 0; i <= 8; i++) {
  performChecks(wordsArrays, wordsArrays);
}

console.log("veryVeryBigData: ", veryVeryBigData);

Your insight and feedback would be highly valued!

Answer №1

When you use "magazine.indexOf(w)", it's like diving into a sea of memory, looking for the treasure known as value 'w'. It's a random process because you never know which memory cell holds the sought-after value. The speed at which you find 'w' can vary - sometimes quick, sometimes slow - depending on how many memory cells you have to search through in this random quest. This fluctuation in speed directly impacts the overall time it takes to locate the desired data.

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 way to generate random numbers for two separate arrays simultaneously?

I have made some progress, but the issue is that both arrays are displaying randomly generated numbers instead of different ones for each array. import java.util.Scanner; public class Prog2_b { public static void main(String[] args) { Sca ...

Implement dynamic routes within your Nuxt single page application once it has been generated

I'm currently exploring the possibility of implementing dynamic routes in a Nuxt SPA. While I am familiar with using dynamic routes in Universal Mode and generating them during build time through functions, I am searching for a solution that does not ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

The return value of a jQuery post request is consistently false

When I click on a tag, my code returns true but the data variable is false. Can you explain why this is happening? $('#AddProvince').click(function () { var url = '@Url.Action("SetProvinceList")'; var id = $('#Province&apo ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

Center a form on the page by adjusting its width and height dimensions

As a newbie to web development, I'm struggling with positioning my form at the center of the content. The form has a width of 930px and its height ranges between: min-height: 450px; max-height: 860px; I have tried different methods but haven't ...

Change the color of the line segment connecting two points on a line

In my three.js project, I am working on drawing a line based on an array of vertices. One challenge I am facing is setting the color of the line to a specific value between two points along the line that are not actual vertices. These two points exist at a ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

Is it considered acceptable to modify classes in a stateless React component by adding or removing them?

My stateless component functions as an accordion. When the container div is clicked, I toggle a couple of CSS classes on some child components. Is it acceptable to directly change the classes in the DOM, or should I convert this stateless component to a ...

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

How a JavaScript Alert is disrupting the design of my ASP.NET Web Application

Despite finding a similar question, the provided answer did not resolve my issue. This is how my application typically appears: However, after triggering a JavaScript alert, the width of menu items becomes distorted and an additional part is added to the ...

Creating a dynamic Three.js fullscreen application with a responsive web form and text overlay

(Just to clarify, I'm seeking advice on how to make my app responsive, not asking how to create it) I've been developing a web application that utilizes Three.js to display a scene across the entire window. My goal is to incorporate a configurat ...

Using Django to retrieve data from a file uploaded through a website

Looking to create a website that allows users to select a local file (XML/JSON) and then navigate to a Django view to extract data from it. Should I implement javascript for the file selection form and sending it to a specific URL for the Django view? Any ...

Developing arrays within QuickTest Pro

I'm working on creating an array of integers in QTP (specifically 9, 16, 25, 34, and 43). I believe the code to initialize it is as follows (though I may be mistaken since I haven't made an array in QTP before), Dim pages(5) pages(0) = 9 pages(1 ...

Using Cocoon Gem in Rails 5 to create nested forms within nested forms

Currently, I am experimenting with the cocoon gem to construct nested forms efficiently. Within my application, I have defined models for Organisation, Package::Bip, and Tenor. The relationships between these models are as follows: Organisation has_ma ...

Using Angular 2 to dynamically bind attribute names

I am facing an issue with a code block in Angular 2. Here is the code: <div *ngFor="let elm of elms; let i = index" [attr.name]="name" text-center> {{elm }} </div> Everything works well. However, I encountered a problem when trying to ...

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...

Utilizing a combination of Mongo, Mongoose, Multer, and FS for deleting images

Looking at the code snippet below:- var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done app.delete("/element/:id", function(req, res) { Image.findByIdAndRemove(req.params.id, function(err) { if(e ...

Bot is being inundated with messages containing no content

My discord.js version is 14.0.3. I'm facing an issue where the message content is not being retrieved correctly. To solve this, I set up a client.on('messageCreate') event handler: client.on('messageCreate', async (message) => ...

Recognizing a component through various page loads

The title of this question may not be the best, but I hope my explanation clarifies what I'm trying to achieve. It's 4AM, so please forgive any confusion in my message. What I want to do is identify if a user-selected element appears on any page ...