The impact of using 'new Function' on performance

When I utilize AJAX to load a script file and run its content, my approach involves the following:

new Function('someargument',xhr.responseText)(somevalue);

However, MDN states the following:

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function and calling it within your code, because functions declared with the function statement are parsed with the rest of the code.

To me, this concept is a bit puzzling. Even if a function is explicitly declared, it still needs to be parsed from the string format of the file, so why would using new Function on a loaded string be considered inefficient?

This issue stirs more curiosity in me rather than concern. While I understand the complications that come with re-parsing the same string in a loop, for a scenario like this one, should there be any significant drawbacks?

Answer №1

To simplify, what I gather from their explanation is that if you incorporate the function constructor into your script like this:

new Function('bar', 'console.log(bar);'));

Essentially, the function's content undergoes two rounds of parsing: first as a string during code loading, and then again when the function is generated during runtime. In your scenario, you're generating the function based on an ajax response post-parsing, making it a unique situation altogether.

Answer №2

I believe the MDN documentation is alluding to a process similar to this:

var x = new Function("return 6;");

Instead of:

function x() { return 6; }

The former method may be less efficient because it initially generates a physical String object ("return 6") using JavaScript, and then interprets that string to form a Function object. The latter interprets the code directly without an intermediary string.

However, in your scenario, since you are dynamically loading the JavaScript code, there might not be a way to avoid this inefficiency.

Answer №3

While I cannot speak for the author's original intentions in that MDN article, one possible interpretation could be considered.

Many contemporary JavaScript interpreters employ an optimizing compiler to generate native code efficiently.

For instance, details on "JavaScriptCore, the WebKit JS implementation" elaborate:

In this scenario, there exists tiered compilation involving three forms: initial parsing and compiling leading to bytecode generation, which can be fine-tuned using method JIT, followed by optimization with DFG JIT. Nonetheless, in reality, on most platforms, the interpreter is omitted, causing all code to undergo method JIT execution.

An optimizing compiler can conduct a wider range of optimizations based on its comprehensive understanding of the code being compiled. Consequently, highly optimized functions can result. For example, if it is known that every function reference immediately calls the function with a string argument within a strict function context, the necessity to allocate a function object may be obviated, allowing for optimizations within its body.

Notably, when invoking new Function, necessary contextual information might be lacking for the optimizing compiler to implement such optimizations and others.

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

Traverse through deeply nested objects and combine into a single string using the Lodash library

Currently, I am utilizing Lodash to streamline object manipulation. Within my object, there are three nested objects that I would like to iterate through, combining all of their respective children in various combinations. The goal is to include only one i ...

Retrieve data from MySQL output in a separate file

In one of my functions, I need to access a variable called "result" which contains the query results. However, when I try to access it from another file where I am processing the output after making a POST Request, the variable is showing up as "undefined" ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

How can I perform a string search that doesn't take into account accented characters

Looking for a way to treat accented characters as equivalent to their non-accented counterparts in my code. Here's what I have so far: var re = new RegExp(string, 'i'); if(target.search(re) == 0) { } Currently, the code ignores the charact ...

Troubleshooting Problems with File Upload Response in ASP.Net MVC Ajax.BeginForm

I have implemented a modal feature that allows users to upload a file. I am looking for a JSON response to indicate whether the upload was successful or not, and then display this information to the end user. Here is my current View: @model int <div ...

Three.js: Plane visibility fluctuates with time

I've been working on a Three.js project where I created a rotating plane. However, I encountered an issue where the plane doesn't display half of the time. To better illustrate this problem, I have created a demonstration in this fiddle. ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Loading a new view within AngularJS using the ng-view directive opens up a fresh

I am currently working on integrating Angular with a REST API for the login process. After successfully setting up Angular with my REST calls, I aim to redirect to a new page upon successful login. In my success handler, I have implemented the following ...

Maneuvering through JavaScript pop-up boxes in Selenium using Python

Currently, I am working on automating a webpage using Selenium webdriver in Python. However, the process encounters a Captcha verification at one point. To surpass this obstacle, I decided to manually input the Captcha through a JavaScript dialog box pop-u ...

Executing tasks in a While loop with NodeJS and attaching actions to a Promise

I am relatively new to incorporating Promises in NodeJS. My current task involves creating a promise dynamically with multiple actions based on the characters found in a string. //let actions = []; getPromise = get(srcBucket, srcKey); // Retrieve the imag ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

Which method is more appropriate for my request - GET or POST? Or should I consider

Recently, I've been exploring the world of get and post methods and could use some guidance! Within my App.js file, there is a user text input field and a submit button. I have a couple of tasks in mind for handling this information: Retrieve a str ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

Can I use jqPlot to create a separate division for the legend?

Is it feasible to move the legend to a distinct div using jqPlot? legend: { show: true, placement: 'outside', fontSize: '11px', location: 'n' } ...

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Refreshing chord chart information from a JSON source in d3.js

I have two functions that are responsible for creating and drawing a D3 chord diagram representing the netflow between different IP addresses in our network. Function 1 (for creating the chord diagram) function createChords(jsonURL, containerID, tooltipI ...

Issue with template updating when utilizing ui-router and ion-tabs in Ionic framework

CODE http://codepen.io/hawkphil/pen/LEBNVB I have set up two pages (link1 and link2) accessible from a side menu. Each page contains 2 tabs: link1: tab 1.1 and tab 1.2 link2: tab 2.1 and tab 2.2 To organize the tabs, I am utilizing ion-tabs for each p ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...