What could be causing such a significant variance in performance for a wrapped JavaScript function?

Here is a code snippet that I have been experimenting with:

function Run () {
  var n = 2*1e7;
  var inside = 0;
  while (n--) {
    if (Math.pow(Math.random(), 2) +
        Math.pow(Math.random(), 2) < 1)
      inside++;
  }

  return inside;
}

var start = Date.now();
Run();
console.log(Date.now() - start);

Initially, the output time is around 335ms. Quite impressive! However, when I enclose the Run function within an anonymous self-invoking function like this:

var d = Date.now();
(function Run () {
  var n = 2*1e7;
  var inside = 0;
  while (n--) {
    if (Math.pow(Math.random(), 2) +
        Math.pow(Math.random(), 2) < 1)
      inside++;
  }

  return inside;
})();
console.log(Date.now() - d);

The output drastically increases to 18319ms. This performance degradation is perplexing. Do you know why this happens?

Just for reference, I am running these snippets on Chrome 26.0.1410.63 console. Interestingly, both versions perform well in the node.js console.

Answer №1

When it comes to optimization, there is no difference between function declarations and function expressions. It would be absurd to think otherwise.


To execute code in Google Chrome's console, a with statement is used as shown below:

 with ((console && console._commandLineAPI) || {}) {
      //Your code goes here
 }

Due to function declarations being hoisted, the previous code will essentially look like this:

function Run () {
  var n = 2*1e7;
  var inside = 0;
  while (n--) {
    if (Math.pow(Math.random(), 2) +
        Math.pow(Math.random(), 2) < 1)
      inside++;
  }

  return inside;
}

with ((console && console._commandLineAPI) || {}) {
  var start = Date.now();
  Run();
  console.log(Date.now() - start);
}

Therefore, the declaration runs outside the with statement. In reality, having a function declaration inside a block is not valid syntax, as stated in the ECMAScript documentation.

For historical reasons, V8 hoists the declaration outside of the with statement instead of causing a syntax error:

var i = 3;

with({i:4}) {
    function test() {
        console.log(i);
    }
}
test();//logs 3 demonstrating that it is **not** influenced by the `with` statement

Since the declaration is not within the with statement, it runs much faster. The With statement is not optimizable under V8 and also disrupts lexical scoping.


*Not optimizable means that the optimizing compiler does not analyze the code, only the generic compiler generates code for the function. This can be compared to Firefox's interpreter mode versus JIT mode. To learn more about language features that inhibit optimization in V8, refer to the optimization killers guide.

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

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

What strategies can I use to prevent the need to create new instances of my service and repository for every

Currently, I am delving into the world of JavaScript using the Express.js Framework. My current learning project involves creating a simple restaurant application to grasp the ins and outs of CRUD operations related to ingredients. I have meticulously craf ...

Is it possible for Nextjs routing catchAll to coexist with a slug folder within a route?

When converting my pages to ISR, I encountered an issue with handling params and dynamic routes. One example is where article/?pageNumber=2 needs to be rewritten as article/2 in middleware for improved performance. However, this change in routing structure ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

What is the best way to pass the setState value to the useEffect hook?

After watching a Youtube video, I took on the challenge of creating my own recipe app using React.js as a beginner. I have been troubleshooting for the past 2 days and seem to have hit a roadblock. The issue lies in passing the value of my state to the use ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

What is the best way to apply the CssClass "active" when clicking on a link

How can we update the cssClass of a link button on each click event, considering that the page refreshes every time? Currently, when I click on any LinkButton, the default behavior sets the cssClass to Plus LinkButton. ---index.aspx----------- <ul cl ...

Regular expressions for capturing login usernames

I recently worked on a web chat project where I utilized socket.io for real-time message sending and receiving. One of the requirements was to capture user logins if they were mentioned within the conversation. Though being a beginner, I attempted to use ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

Incrementing values in ng-repeat object automatically

My project involves extracting game information from mlb.com and utilizing angularjs along with the ng-repeat directive to display it. A sample of the JSON feed is shown below. { "data": { "games": { "next_day_date": "2017-08-19", "mo ...

Discover the magic of Google Charts with the ability to showcase HTML source code within tooltips

I am attempting to show a Pie Chart using Google Charts with HTML in the tooltips, but I am encountering an issue where the HTML source is visible. I have tried setting html:true on the data column and tooltip.isHtml in the options, but I am unsure of what ...

How can I include line breaks using HTML `<br>` tags in a textarea field that is filled with data from a MySQL

Within a modal, I am showcasing a log inside a read-only <textarea> field that contains data fetched from my MySQL database. Below this, there is a writable <textarea> field where users can input updates to the log, which are then added to the ...

The image failed to load in React/Express

I'm currently working on a React/Express app and I've encountered an issue with images not loading. Instead, I see the message "could not load the image." The CSS styles are loading fine, but the images are not showing up. I suspect there might ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Locate the nearest upcoming date and time to today's date in the JSON response

I am currently working with an API that provides a response containing the `start_time` field in JSON format. My goal is to extract the ID from the JSON object whose next date time is closest to the current date and time, excluding any dates from the past. ...

Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time. I've successfully managed to track one variable, but not both simultaneously. $scope.color_slider_bar = { value:0, minValue: 0, maxValue: ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...