Home > Article > Web Front-end > Comprehensive 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:
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
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
• 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
According to the principle of monitoring events introduced above, let’s rewrite it
当然,我们不必每次都做事件源的判断工作,可以将其抽象一下交给工具类来完成。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.