Home >Web Front-end >JS Tutorial >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:
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)
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
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
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
var child = docuemnt.createElement("li");
child.innerHtml = "child";
document.getElementById("parent").appendChild(child);
}
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:
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