Exploring 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:
//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)
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
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
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
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:
$("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

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor
