search
HomeWeb Front-endJS TutorialExploring Javascript execution efficiency issues_Basic knowledge

Javascript is a very flexible language. We can write various styles of code as we like. Different styles of code will inevitably lead to differences in execution efficiency. During the development process, we are sporadically exposed to many improvement codes. Performance methods, sort out the common and easy-to-avoid problems

 Javascript’s own execution efficiency
Scope chain, closure, prototypal inheritance, eval and other features in Javascript not only provide various magical functions, but also bring various efficiency problems. If used carelessly, they will lead to low execution efficiency.

 1. Global import
We will use some global variables (window, document, custom global variables, etc.) more or less during the coding process. Anyone who understands the JavaScript scope chain knows that accessing global variables in the local scope requires a The entire scope chain is traversed layer by layer until the top-level scope, and the access efficiency of local variables will be faster and higher. Therefore, when some global objects are used frequently in the local scope, they can be imported into the local scope, for example:

Copy code The code is as follows:

//1. Pass in the module as a parameter
(function(window,$){
var xxx = window.xxx;
$("#xxx1").xxx();
$("#xxx2").xxx();
})(window,jQuery);

//2. Temporarily store in local variables
function(){
var doc = document;
var global = window.global;
}

 2. eval and eval-like issues
We all know that eval can process a string as a js code. It is said that code executed using eval is more than 100 times slower than code without eval (I have not tested the specific efficiency, interested students can test it)

JavaScript code will perform a similar "pre-compilation" operation before execution: it will first create an active object in the current execution environment, and set those variables declared with var as attributes of the active object, but at this time these variables The assignment values ​​are all undefined, and those functions defined with function are also added as properties of the active object, and their values ​​are exactly the definition of the function. However, if you use "eval", the code in "eval" (actually a string) cannot recognize its context in advance and cannot be parsed and optimized in advance, that is, precompiled operations cannot be performed. Therefore, its performance will also be greatly reduced

In fact, people rarely use eval nowadays. What I want to talk about here are two eval-like scenarios (new Function{}, setTimeout, setInterver)

Copy code The code is as follows:

setTimtout("alert(1)",1000);
setInterver("alert(1)",1000);
(new Function("alert(1)"))();

The execution efficiency of the above types of codes will be relatively low, so it is recommended to directly pass in anonymous methods or method references to the setTimeout method

 3. After the closure ends, release variables that are no longer referenced

Copy code The code is as follows:

var f = (function(){
var a = {name:"var3"};
var b = ["var1","var2"];
var c = document.getElementByTagName("li");
//****Other variables
//***Some operations
var res = function(){
alert(a.name);
}
Return res;
})()

The return value of variable f in the above code is the method res returned in the closure composed of an immediately executed function. This variable retains references to all variables (a, b, c, etc.) in this closure, so These two variables will always reside in the memory space, especially the reference to the dom element, which will consume a lot of memory. However, we only use the value of the a variable in res, so before the closure returns, we can Release other variables

Copy code The code is as follows:

var f = (function(){
var a = {name:"var3"};
var b = ["var1","var2"];
var c = document.getElementByTagName("li");
//****Other variables
//***Some operations
//Release variables that are no longer used before the closure returns
b = c = null;
var res = function(){
alert(a.name);
          }
Return res;
})()

The efficiency of Js operating dom
In the process of web development, the bottleneck of front-end execution efficiency is often in DOM operation. DOM operation is a very performance-consuming thing. How can we save performance as much as possible during DOM operation?

1. Reduce reflow
What is reflow?
When the properties of a DOM element change (such as color), the browser will notify render to redraw the corresponding element. This process is called repaint.

If the change involves element layout (such as width), the browser discards the original attributes, recalculates and passes the results to render to redraw the page elements. This process is called reflow.

Methods to reduce reflow
First delete the element from the document, and then put the element back to its original position after completing the modification (when a large number of reflow operations are performed on an element and its sub-elements, the effects of methods 1 and 2 will be more obvious)
Set the display of the element to "none", and then change the display to the original value after completing the modification
When modifying multiple style attributes, define a class class instead of modifying the style attributes multiple times (recommended for certain students)
Use documentFragment
when adding a large number of elements to the page ​For example

Copy code The code is as follows:

for(var i=0;i

var child = docuemnt.createElement("li");

child.innerHtml = "child";

document.getElementById("parent").appendChild(child);

}



When the code needs to access the status information of an element multiple times, we can temporarily store it in a variable if the status remains unchanged. This can avoid the memory overhead caused by multiple accesses to the DOM. A typical example is:

When searching for DOM elements, try to avoid traversing large areas of page elements, try to use precise selectors, or specify context to narrow the search scope, take jquery as an example

Use less fuzzy matching selectors: such as $("[name*='_fix']"), and more use compound selectors such as id and gradually narrowing the range $("li.active"), etc.
Specify context: such as $("#parent .class"), $(".class",$el), etc.

4. Use event delegation
Usage scenario: A list with a large number of records. Each record needs to be bound to a click event to implement certain functions after the mouse is clicked. Our usual approach is to bind a listening event to each record. This approach will cause the page There will be a large number of event listeners, which will be inefficient.

Basic principle: We all know that events in the DOM specification will bubble up, which means that without actively preventing event bubbling, the events of any element will bubble up to the top step by step according to the structure of the DOM tree. The event object also provides event.target (srcElement under IE) to point to the event source, so even if we listen to the event on the parent element, we can find the original element that triggered the event. This is the basic principle of delegation. Without further ado, here’s an example

Based on the principle of monitoring events introduced above, let’s rewrite it

Of course, we don’t have to judge the event source every time. We can abstract it and leave it to the tool class to complete. The delegate() method in jquery implements this function

The syntax is like this $(selector).delegate(childSelector, event, data, function), for example:

Copy code The code is as follows:

$("div").delegate("button","click",function(){
$("p").slideToggle();
});

Parameter description (quoted from w3school)
Parameter Description
childSelector required. Specifies one or more child elements to which event handlers are attached.
event is required. Specifies one or more events to attach to the element. Multiple event values ​​separated by spaces. Must be a valid event.
data is optional. Specifies additional data to be passed to the function.
function required. Specifies a function to run when an event occurs.
Tips: Another benefit of event delegation is that even events triggered on elements dynamically added after event binding can also be monitored, so you don’t have to bind events to elements every time they are dynamically added to the page

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.