Home  >  Article  >  Web Front-end  >  Comprehensive summary of Javascript execution efficiency_Basic knowledge

Comprehensive summary of Javascript execution efficiency_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:17:48976browse

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<100: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<100: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