search
HomeWeb Front-endJS TutorialComprehensive summary of Javascript execution efficiency_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
The scope chain, closure, prototype inheritance, eval and other features in Javascript not only provide various magical functions but also bring Various efficiency issues arise, and careless use 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. People who understand the javascript scope chain As we all know, accessing global variables in a local scope requires traversing the entire scope chain layer by layer until the top-level scope, and the access efficiency of local variables will be faster and higher, so some global objects are frequently used in the local scope. It can be imported into the local scope, for example:

Copy the 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 save to local variables
function(){
var doc = document;
var global = window.global;
}

2. eval and eval-like issues
We all know that eval can convert a string It is executed as js code. It is said that the code executed using eval is more than 100 times slower than the 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)

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 Code 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 in a closure composed of an immediately executed function The returned method res, 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 references to DOM elements. The consumption will be very large, and we only use the value of the a variable in res, so we can release other variables before the closure returns
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
//Close Release variables that are no longer used before the package returns
b = c = null;
var res = function(){
alert(a.name);
}
return res;
})()

Efficiency of JS operating DOM
In the web development process, the bottleneck of front-end execution efficiency is often in DOM operation, which is very performance-intensive How can we save performance as much as possible during DOM operation?

1. Reduce reflow
What is reflow?
When the attributes 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
1. 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 effect of the two methods 1 and 2 will be more obvious)

2. Set the display of the element to "none", and then change the display to the original value after completing the modification

3 .When modifying multiple style attributes, define a class class instead of modifying the style attribute multiple times (recommended for certain students)

4. 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);
}

The above code will operate the dom multiple times and is relatively inefficient. You can change it to the following form to create a documentFragment. Adding all elements to the docuemntFragment will not change the dom structure. , and finally add it to the page, with only one reflow
Copy code The code is as follows:

var frag = document.createDocumentFragment();
for(var i=0;i var child = docuemnt.createElement("li");
child.innerHtml = " child";
frag.appendChild(child);
}
document.getElementById("parent").appendChild(frag);

2. Temporary storage DOM status information
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:
Copy code The code is as follows:

var lis = document.getElementByTagName ("li");
for(var i=1;i //***
}

The above method will be Each loop accesses the dom element. We can simply optimize the code as follows:
Copy the code The code is as follows:

var lis = document.getElementByTagName("li");
for(var i=1,j=lis.length ;i //***
}

3. Narrow the search scope of the selector
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, taking jquery as an example

• Use less fuzzy matching selectors: For example $("[name*='_fix']"), use more compound selectors such as id and gradually narrowing the range $("li.active ") etc.

•Specify context: For example $(“#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 a mouse click. This is our usual approach It is to bind listening events to each record. This approach will result in a large number of event listeners on the page, which is relatively inefficient.

Basic principle: We all know that events in the DOM specification will bubble up, which means that without actively preventing the event from bubbling, the event of any element will Bubble 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 is the example

Copy code The code is as follows:

$("ul li ").bind("click",function(){
alert($(this).attr("data"));
})

The above writing method is actually for All li elements are bound to click events to listen for mouse clicks on each element, so there will be a large number of event listeners on the page.

According to the principle of monitoring events introduced above, let’s rewrite it

Copy the code The code is as follows:

$("ul").bind("click",function(e){
if(e.target.nodeName.toLowerCase() ==="li"){
alert($( e.target).attr("data"));
}
})

这样一来,我们就可以只添加一个事件监听器去捕获所有li上触发的事件,并做出相应的操作。

当然,我们不必每次都做事件源的判断工作,可以将其抽象一下交给工具类来完成。jquery中的delegate()方法就实现了该功能

语法是这样的$(selector).delegate(childSelector,event,data,function),例如:

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

Parameter description (quoted from w3school)

参数 描述
childSelector 必需。规定要附加事件处理程序的一个或多个子元素。
event 必需。规定附加到元素的一个或多个事件。由空格分隔多个事件值。必须是有效的事件。
data 可选。规定传递到函数的额外数据。
function 必需。规定当事件发生时运行的函数。

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 elements every time they are dynamically added to the page. event.

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
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.