Is it possible for a JavaScript loop using a for statement to decrease in speed after reaching 2.1 billion iterations

As I delved into benchmarking JavaScript and .NET Core to select a server-side framework for offering specific RESTful services that required iterating through large arrays (approximately 2.1 billion), an interesting observation caught my attention. While experimenting with some simple code, I noticed unusual behavior in Node.js after reaching a certain number of iterations. To validate this finding, I conducted tests on various platforms including:

  • macOS Catalina (Node.js v12.18) - Intel Core i9 4GHz 6 core
  • Linux CentOS 7 (Node.js v12.18) VM - Intel Core i9 4GHz 2 core
  • Google Chrome Version 84.0.4147.105 (Official Build) (64-bit)
  • Mozilla Firefox version 78.2

Upon viewing the running video, it became evident that there was a surprising doubling in processing time from 300ms to 600ms.

Sample Codes:

1. Node.js:

var cnt = 0;
var logPeriod=100000000;
var max=10000000000;
for (let i = 0; i < max; i++) {
  if (i % logPeriod === 0) {
    // var end = Date.now();
    if (i !== 0) {
      console.timeEnd(cnt*logPeriod, i);
      cnt++;
    }
    console.time(cnt*logPeriod);
  }
}

2. Browser:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function doloop() {
        var cnt = 0;
        var logPeriod = 100000000;
        var max = 10000000000;
        for (let i = 0; i < max; i++) {
          if (i % logPeriod === 0) {
            // var end = Date.now();
            if (i !== 0) {
              console.timeEnd(cnt * logPeriod, i);
              cnt++;
            }
            console.time(cnt * logPeriod);
          }
        }
      }
    </script>
  </head>
  <body>
    <button onclick="doloop()">doloop</button>
  </body>
</html>

Answer №1

Hello, I am a developer working with the V8 engine.

When it comes to optimizing code, V8's compiler prioritizes using 32-bit integers for numbers whenever possible. However, if a number surpasses the int32 range or requires more precision, the optimized code will switch to using 64-bit doubles as mandated by the JavaScript specification. This means that arithmetic operations, even simple ones like i++, are slower when dealing with 64-bit doubles compared to 32-bit integers due to hardware limitations.

Despite this internal difference, from an external perspective, numbers always function as if they were 64-bit doubles. It is important to note that engines do not always internally use 64-bit doubles, as demonstrated by the performance advantage of utilizing 32-bit integers when feasible.

If you need to choose between JavaScript and .NET for handling restful services that involve iterating through large arrays (approximately 2.1 billion elements), which one would you select?

The clear choice in this scenario would be to utilize .NET. The V8 engine (and consequently Node.js) imposes limits on creating arrays with such a massive number of elements, as the per-object size threshold is much lower. While initial array creation may seem successful with syntax like var a = new Array(2_100_000_000), attempting to fill in all elements will likely lead to a crash after some time.

If your actual arrays are not expected to reach such extreme sizes, it would be beneficial to conduct benchmarks that align closely with your typical workload. This approach will yield results that better reflect reality and aid in making informed decisions going forward.

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

Optimizing Three JS computeVertexNormals() for Improved Performance

I have a massive buffer geometry consisting of approximately 4 million vertices that requires a small area of shading to be updated. Currently, I randomly update the vertex normals causing lag. I attempted using updateRange.offset on the geometry but it se ...

Modify the href value by matching it with the parent div attribute

I am working on an HTML project <div class="1" style="" title="NeedthisText TextIDontneed"> <div class="2> <div class="3"> <a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1"></a> </div> </div> &l ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

"Mastering the art of passing variables within the index parameter for JavaScript push method

I need help passing a variable inside index in JavaScript push while working with Angular. Here is my current code: angular.forEach(Val, function (Value,Key) { angular.forEach(Value, function (Value1,Key1) { saveDetailArr.push({ 'option_i ...

Validation of drop-down lists

How can I validate whether a TextBox is empty when a Dropdown list's selected index changes in ASP.NET using validation controls? ...

Understanding the functionality of app.listen() and app.get() in the context of Express and Hapi

What is the best way to use only native modules in Node.js to recreate functionalities similar to app.listen() and app.get() using http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype.get = function(call ...

Why is the jQuery Ajax AutoComplete feature not functioning properly?

Hey there, I'm currently utilizing CodeIgniter along with Ajax AutoComplete for jQuery in my project. When setting up my autocomplete feature in jQuery, I used the following code: a = $('.city').autocomplete({ serviceUrl: "<? echo $ ...

What is the best way to retrieve and parse XML using node.js?

Is there a way to fetch an XML file from the internet using node.js, and then parse it into a JavaScript object? I've looked through the npm registry but can only find examples on parsing XML strings, not fetching them. ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Creating protected routes in ReactJs using Typescript by utilizing a Higher Order Component (HOC) as

I'm struggling to create a basic HOC that can protect a component, ensuring that the user is logged in before rendering the component. Below is my attempt at building the protective HOC (not functional yet). export default function ProtectedRoute(Com ...

The video.play() function encountered an unhandled rejection with a (notallowederror) on IOS

Using peer.js to stream video on a React app addVideoStream(videoElement: HTMLVideoElement, stream: MediaStream) { videoElement.srcObject = stream videoElement?.addEventListener('loadedmetadata', () => { videoElement.play() ...

How can I control audio playback with just a click on an image on an HTML webpage?

I attempted to use a code from this website, but it doesn't seem to be working for me. I was hoping that someone here could lend a hand. The code I tried makes the song play when I click the gif image, but when I click it again, it just restarts. H ...

Using React to showcase an array of objects in a table with row spanning

I'm facing a challenge with displaying adjustedAmount, paidAmount, and cost type in a table where one row is divided into multiple costs. Can someone help me figure out how to do this? Below is the object I need to work with: const datdfa = [ { ind ...

Methods for sending an indexed array object back to a getJSON request with jquery

When sending an Indexed Array to a PhP file on the server side using getJSON, it seems like using an associated array may be a better choice. However, the indexed array works fine and the data is successfully received on the server. I am able to process th ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

modify the text inside a div when a radio button is clicked

Can someone help me with updating the status div based on the radio button value selected by the user? The code below isn't functioning as expected. Any assistance is appreciated. Thank you! Here is the HTML code snippet: <form action=""> ...

Leveraging AJAX to assist in PHP for data parsing

I am currently exploring the world of AJAX and grappling with a unique situation. I am in the process of developing an HTML app that will be integrated into a mobile application using PhoneGap. The main objective of my project is for the HTML page to con ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...