Sharing examples of JS performance optimization techniques
-
The script should be placed after the page element code
No matter whether the current JavaScript code is embedded or in an external link file, the downloading and rendering of the page must stop and wait for the script Execution complete. The longer the JavaScript execution process takes, the longer the browser waits to respond to user input. The reason why browsers block when downloading and executing scripts is that the script may change the namespace of the page or JavaScript, which will affect the content of subsequent pages.
-
Avoid global lookup
function search() { //当我要使用当前页面地址和主机域名 alert(window.location.href + window.location.host); } //最好的方式是如下这样 先用一个简单变量保存起来 function search() { var location = window.location; alert(location.href + location.host); }
-
Type conversion
般最好用”" + 1来将数字转换成字符串,虽然看起来比较丑一点,但事实上这个效率是最高的,性能上来说:
("" + ) > String() > .toString() > new String() "
" var myVar = "3.14159", str = "" + myVar, // to string num=+myVar, // to number i_int = ~ ~myVar, // to integer f_float = 1 * myVar, // to float b_bool = !!myVar, /* to boolean - any string with length and any number except 0 are true */ array = [myVar]; // to array "
-
Multiple type declarations
All variables can be used in JavaScript Declared with a single var statement, it is a combined statement to reduce the execution time of the entire script. Just like the above code, the above code format is also quite standardized, making it clear at a glance.
#Clone through template elements instead of createElement - Many people like to use document.write in JavaScript to generate content for the page. In fact, this is less efficient. If you need to insert HTML directly, you can find one. Container elements, such as specifying a p or span, and setting their innerHTML to insert their own HTML code into the page. Usually we may use strings to write HTML directly to create nodes. In fact, 1: the code cannot be guaranteed. Effectiveness, 2: String operation efficiency is low, so the document.createElement() method should be used. If there are ready-made template nodes in the document, the cloneNode() method should be used, because after using the createElement() method, you need To set the attributes of multiple elements, use cloneNode() to reduce the number of attribute settings - also if you need to create many elements, you should prepare a template node first
var frag = document.createDocumentFragment(); for (var i = 0; i < 1000; i++) { var el = document.createElement('p'); el.innerHTML = i; frag.appendChild(el); } document.body.appendChild(frag); //替换为: var frag = document.createDocumentFragment(); var pEl = document.getElementsByTagName('p')[0]; for (var i = 0; i < 1000; i++) { var el = pEl.cloneNode(false); el.innerHTML = i; frag.appendChild(el); } document.body.appendChild(frag);
Be careful when using closures. Package - Case of closure
document.getElementById('foo').onclick = function(ev) { };
Combining control conditions and control variables when looping - When we want to add something to this Before looping, we found that there are several operations that the JavaScript engine needs to occur in each iteration: 1: Check whether x exists 2: Check whether x is less than 10 3: Increase x by 1Improvement
var x = 9; do { } while( x-- );
Avoid comparing to null - Since JavaScript is weakly typed, it does not do any automatic type checking, so if you see code that compares to null, try Use the following techniques to replace: 1. If the value should be a reference type, use the instanceof operator to check its constructor 2. If the value should be a basic type, use typeof to check its type 3. If it is an object Contains a specific method name, use the typeof operator to ensure that the method with the specified name exists on the object Respect the ownership of the object
- Because JavaScript can Modifying any object can override the default behavior in unpredictable ways, so if you are not responsible for maintaining an object, its objects or its methods, then you should not modify it. Specifically: 1. Do not add attributes to instances or prototypes. 2. Do not add methods to instances or prototypes. 3. Do not redefine existing methods. 4. Do not repeatedly define methods that have been implemented by other team members. Never modify them. From the objects you own, you can create new functionality for the object by: 1. Creating a new object containing the required functionality and using it to interact with related objects 2. Creating a custom type and inheriting the type that needs to be modified, You can then add extra functionality to the custom type Use literals
- Shorten negative detection
-
-
巧用||和&&布尔运算符
function eventHandler(e) { if (!e) e = window.event; } //可以替换为: function eventHandler(e) { e = e || window.event; } if (myobj) { doSomething(myobj); } //可以替换为: myobj && doSomething(myobj);
switch语句相对if较快
每条语句末尾须加分号
for ( var x = 0; x < 10; x++ ) {};
var aTest = new Array(); //替换为 var aTest = []; var aTest = new Object; //替换为 var aTest = {}; var reg = new RegExp(); //替换为 var reg = /../; //如果要创建具有一些特性的一般对象,也可以使用字面量,如下: var oFruit = new O; oFruit.color = "red"; oFruit.name = "apple"; //前面的代码可用对象字面量来改写成这样: var oFruit = { color: "red", name: "apple" };
if (oTest != '#ff0000') { //do something } if (oTest != null) { //do something } if (oTest != false) { //do something } //虽然这些都正确,但用逻辑非操作符来操作也有同样的效果: if (!oTest) { //do something }
随着实例化对象数量的增加,内存消耗会越来越大。所以应当及时释放对对象的引用,让GC能够回收这些内存控件。 对象:obj = null 对象属性:delete obj.myproperty 数组item:使用数组的splice方法释放数组中不用的item
相关推荐:
The above is the detailed content of Sharing examples of JS performance optimization techniques. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

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),