Deep understanding of JavaScript memory and performance issues

WBOY
Release: 2022-03-31 11:44:47
forward
2035 people have browsed it

This article brings you relevant knowledge aboutjavascript, which mainly introduces the memory and performance issues of JavaScript, including how to solve problems like too many buttons, deleting event handlers, etc. Wait, I hope it helps everyone.

Deep understanding of JavaScript memory and performance issues

Related recommendations:javascript tutorial

1. What is JavaScript memory and performance

Because of the event handler Interactions are possible in modern web applications, so many developers make the mistake of using them heavily in their pages. In JavaScript, the number of event handlers in a page is directly related to the overall performance of the page. There are many reasons, such as ① each function is an object and takes up memory space. The more objects there are, the worse the performance; ② The number of DOM visits required for a specified event handler will first cause a delay in the entire page interaction.

2. Talk about the performance issues of innerHTML?

1. Negative teaching materials for using innerHTML

for(let value of values){ ul.innerHTML += '
Copy after login
  • ${value}
  • ';}

    This code is inefficient because innerHTML must be set once for each iteration. Not only that, it must be set for each loop. Read innerHTML first, which means that innerHTML needs to be accessed twice in one loop.

    2. How to solve

    let itemsHtml = "";for(let value of values){ itemsHtml += '
    Copy after login
  • ${value}
  • ';}ul.innerHTML = itemsHtml;

    After this modification, the efficiency will be much higher. Only innerHTML will be assigned once. The following code can also be done:
    ul.innerHTML = values.map(value => '

  • ${value}
  • ').join(' ');

    3. How Solve the problem of too many buttons?

    The solution to too many event handlers is to use event delegation. Event delegation leverages event bubbling, allowing you to use only one event handler to manage one type of event. For example, the click event bubbles up to the document. This means that you can specify an onclick event handler for the entire page, rather than specifying separate event handlers for each clickable element.

    
            
    Copy after login
    • 比比东
    • 云韵
    • 美杜莎

    This contains three list items, which should perform a certain operation when clicked. The usual way is to specify three event handlers:

    let item1 = document.getElementById("girl1");let item2 = document.getElementById("girl2");let item3 = document.getElementById("girl3");item1.addEventListener("click",(event) => { console.log("我是比比东!");})item2.addEventListener("click",(event) => { console.log("我是云韵!");})item3.addEventListener("click",(event) => { console.log("我是美杜莎!");})
    Copy after login

    Too much same code, the code is too ugly .
    Using event delegation, just add an event handler to the common ancestor node of multiple elements, and you can solve the ugliness!

    let list = document.getElementById("myGirls");list.addEventListener("click",(event) => { let target = event.target; switch(target.id){ case "girl1": console.log("我是比比东!"); break; case "girl2": console.log("我是云韵!"); break; case "girl3": console.log("我是美杜莎!"); break; }})
    Copy after login

    4. What are the advantages of event delegation?

    • The document object is available at any time, and you can add an event handler to it at any time (without waiting for the DOMContentLoaded or load event), through which it handles all events of some type in the page. This means that as long as the page renders clickable elements, it will work without delay.

    • Save the time spent on setting up page event routines.

    • Reduce the memory required for the entire page and improve overall performance.

    5. Delete the event handler

    After assigning the event handler to an element, a connection is established between the browser code and the JavaScript code responsible for page interaction. . The more such contact resumes, the worse the page performance will be. In addition to limiting such connections through event delegation, unused event handlers should be promptly removed. The poor performance of many web applications is caused by useless event handlers remaining in memory.
    There are two reasons for this problem:

    1. Deleting elements with event handlers

    For example, through the DOM method removeChild() or replaceChild ()Delete node. The most common one is to use innerHTML to replace a certain part of the page as a whole. At this time, if there is an event handler on the element deleted by innerHTML, it will not be cleaned up normally by the garbage collection program.
    Therefore, if you know that an element will be deleted, you should manually delete its event handler, such asbtn.onclick = null;//Delete event handler, event delegation also helps To solve this problem, if you know that an element is to be replaced by innerHTML, don't add an event handler to the element, just add it to a higher-level node.

    2. Page unloading will also cause the problem of residual references in memory

    If the event handlers are not cleaned up after the page is unloaded, they will still remain in the memory. middle. After that, every time the browser loads and unloads the page (such as by going forward, back, or refreshing), the number of residual objects in memory increases because the event handlers are not recycled.
    Generally speaking, it is best to delete all event handlers in the onunload event handler before the page is unloaded. The advantage of event delegation can also be seen at this time. Because there are few event handlers, it is easy to remember which ones to delete.

    六、如何解决循环中动态添加p,造成的死循环问题?

    表达式

    let ps = document.getElementsByTagName("p");for(let i = 0;i

    表达式

    let ps = document.getElementsByTagName("p");for(let i = 0,len=ps.length;i

    表达式①中第一行取得了包含文档中所有

    元素的HTMLCollection。因为这个集合是实时的,所以任何时候只要向页面中添加一个新的

    元素,再查询这个集合就会多一项。因为浏览器不希望保存每次创建的集合,所以就会在每次访问时更新集合。每次循环都会求值i ,这意味着要获取所有

    元素的查询。因为循环体中创建并向文档中添加一个新的

    元素,所以每次循环ps.length的值也会递增。因为两个值都会递增,所以i永远不会等于ps.length,因此表达式①会造成死循环。
    而表达式②中,又初始化了一个保存集合长度的变量len,因为len保存着循环开始集合的长度,而这个值不会随集合增大动态增长(for循环中初始化变量处只会初始化一次),所以就可以避免表达式①中出现的无穷循环问题。
    如果不想初始化一个变量,也可以使用反向迭代:

    表达式

    let ps = document.getElementsByTagName("p");for(let i = ps.length-1;i>=0;--i){ let p = document.createElement("p"); document.body.appendChild(p);}
    Copy after login

    七、JavaScript思维导图

    Deep understanding of JavaScript memory and performance issues

    相关推荐:javascript教程

    The above is the detailed content of Deep understanding of JavaScript memory and performance issues. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:csdn.net
    Statement of this Website
    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
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!