Want to make your JS loop lightning fast?

Today I stumbled upon an interesting idea to test the performance of a loop that I have cleverly named "scoped for". The concept is quite simple. This loop consists of two variables, "i" and "l", which are defined at one scope higher than the loop itself. There is nothing else in those two scopes.

After setting up a jsPerf test, I was amazed by the results. You can check them out here: http://jsperf.com/variable-scoped-loop/6

Encouraged by the jsPerf results, I decided to run a local test, and the results were even better (1000x1000 loops average time of 5s for "standard for" and under 0.01s for "scoped for").

Naturally, I am now curious as to why this loop is performing so exceptionally well. My assumption is that it has something to do with V8, but one can never be too sure.

Is there anyone out there willing to shed some light on this?

TLDR: Why is this loop so astonishingly fast?

var loop = (function() {
                var i, l;

                return function(length, action) {
                    for(i = 0, l = length; i < l; ++i) {
                        action();
                    }
                };
            }());

Answer №1

Unfortunately, there is no magic solution here: it seems that your test is flawed.

When it comes to varInFor, the empty function appears to be called 9999^2 times, while with varInScope, it is only called 9999 times. This discrepancy explains why it finishes much faster. To confirm this, you can simply make the empty function output something.

The underlying reason is that the variables i and l are shared between the outer and inner calls of varInScope. Consequently, once the inner loop concludes, i equals l, causing the outer loop to terminate immediately.

For a revised version, check out another JSPerf that initializes the functions every time (creating a new set of variables in the closure). Surprisingly, this improved version is actually up to 20% slower than the conventional for loop.

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

Locate identical values within an array in MongoDB, even if they exist independently of an object

{ "_id" : ObjectId("15672"), "userName" : "4567", "library" : [ { "serialNumber" : "Book_1" }, { "serialNumber" : "Book_2" }, { "serialNumber" : "Book_4" } ...

Rotating a 3D object in Three.js around any axis using the Loop Rotation feature

I'm currently attempting to create a 3D object that rotates continuously on any axis, similar to a classic cube or sphere. However, I'm encountering an issue where the object is not moving at all and I'm unsure why. Here is the code I'm ...

JavaScript removing elements from an array

In my situation, I am dealing with "scene" and various graphics "objects"... Scene.prototype.objects=new Array(); Scene.prototype.add=function(obj){ var last=this.objects.length; this.objects[last]=obj} Scene.prototype.remove=function(obj){ this.o ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

I'm trying to understand a JSON object that has multiple key names pointing to a single value. How can I properly interpret this in

Encountering an object with a strange key. const obj = { formValues: { 'TOTAL;_null_;_null_;3;_null_': "100" 'billing;_null_;_null_;1;_null_': "Y" 'billing;_null_;_null_;2;_null_': "Y" 'billi ...

PHP variable missing "+" sign at the end after post operation

I have encountered a unique problem that I cannot seem to find anywhere else. My issue lies in adding grades ending with a plus sign, such as B+, C+ or D+. I am able to add grades like A-, B-, C- and D- without any problem, but when it comes to adding a g ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

What is the process for interacting with DOM Elements in Node JS?

JAVASCRIPT FILE const path = require('path'); const http = require('http'); const fs = require('fs'); const dir = '../frontend/'; const server = http.createServer((request, respond) => { console.log(reques ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

Updating a route in Next.js? Make sure to remove the classList as you

Looking to remove a specific class whenever the route changes in Next.js, I've attempted the following approach: React.useEffect(() => { const activatedLink = router.query.tags const classActivated = document.querySelector('.'+activated ...

PHP not able to retrieve JavaScript variable using Ajax

Resolved: I recently discovered that ajax only sends data in that particular moment, and redirecting creates a new instance. I spent hours searching through various Stack Overflow results for solutions, but none of them seem to work. My current challenge ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...

Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and ...

Splitting the package.json file to separate the front-end and back-end components while utilizing shared

Currently, I am working on a project that involves a separate frontend (webpack) and backend (express/mongodb). My goal is to separate the dependencies in the package.json file while still being able to share certain logic/utility code between them. How ca ...

javascript ondrag while self-pressing

Within this div, I have a series of p elements. My goal is to drag the selected element into the input field. Here's an example: var input = document.getElementById("test"); input.addEventListener('drop', function (event) { event.pr ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...