


Some knowledge to effectively improve JavaScript execution efficiency_javascript skills
In order to provide a fresh and unique user experience, many websites use JavaScript to improve design, validate forms, check browsers, Ajax requests, cookie operations, etc., to achieve dynamic effects without refreshing. However, a large amount of content needs to be rendered in the browser, and if it is not handled properly, the website performance will drop sharply. So we need to understand how to improve the execution efficiency of JavaScript.
JavaScript Function
In JavaScript, functions are precompiled before use. Although sometimes strings can be used instead of functions, this JavaScript code will be re-parsed every time it is executed, affecting performance.
1. eval example
eval('output=(input * input)');
// It is recommended to change it to:
eval(new function() { output=(input * input)});
2. setTimeout example
setTimeout("alert(1)", 1000);
// It is recommended to change it to:
setTimeout(function(){alert(1)}, 1000);
Using functions instead of strings as parameters ensures that the code in the new method can be optimized by the JavaScript compiler.
JavaScript scope
Each scope in the JavaScript scope chain contains several variables. It's important to understand scope chaining in order to take advantage of it.
var localVar = "global"; //Global variable
function test() {
var localVar = "local"; //local variable
//Local variables
alert(localVar);
//Global variables
alert(this.localVar);
//If the document cannot be found in local variables, search for global variables
var pageName = document.getElementById("pageName");
}
Using local variables is much faster than using global variables because resolution is slower the further you go in the scope chain. The following figure shows the scope chain structure:
If there are with or try-catch statements in the code, the scope chain will be more complicated, as shown below:
JavaScript String
A function in JavaScript that greatly affects performance is string concatenation. Generally, symbols are used to splice strings. However, early browsers did not optimize this connection method, which resulted in the continuous creation and destruction of strings seriously reducing JavaScript execution efficiency.
var txt = "hello" " " "world";
It is recommended to change it to:
var o = [];
o.push("hello");
o.push(" ");
o.push("world");
var txt = o.join();
Let’s encapsulate it simply:
function StringBuffer(str) {
var arr = [];
arr.push(str || "");
This.append = function(str) {
arr.push(str);
return this;
};
This.toString = function() {
return arr.join("");
};
};
Then call it like this:
var txt = new StringBuffer();
txt.append("Hello");
txt.append(" ");
txt.append("World");
alert(txt.toString());
JavaScript DOM manipulation
HTML Document Object Model (DOM) defines a standard way to access and manipulate HTML documents. It represents an HTML document as a node tree containing elements, attributes, and text content. By using the HTML DOM, JavaScript can access all nodes in an HTML document and manipulate them.
DOM redraw
Every time the DOM object of the page is modified, it involves DOM redrawing, and the browser will re-render the page. Therefore, reducing the number of modifications of DOM objects can effectively improve the performance of JavaScript.
for (var i = 0; i < 1000; i ) {
var elmt = document.createElement('p');
elmt.innerHTML = i;
document.body.appendChild(elmt);
}
It is recommended to change it to:
var html = [];
for (var i = 0; i < 1000; i ) {
html.push('
' i '
');}
document.body.innerHTML = html.join('');
DOM access
Every node in the HTML document can be accessed through the DOM. Every time you call getElementById(), getElementsByTagName() and other methods, the node will be searched and accessed again. Therefore, caching the found DOM nodes can also improve the performance of JavaScript.
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
It is recommended to change it to:
var elmt = document.getElementById("p2");
elmt.style.color = "blue";
elmt.style.fontFamily = "Arial";
elmt.style.fontSize = "larger";
DOM traversal
DOM traversal of child elements usually reads the next child element in a loop according to the index. In early browsers, this reading method has very low execution efficiency. The nextSibling method can be used to improve the efficiency of js traversing DOM.
var html = [];
var x = document.getElementsByTagName("p");//All nodes
for (var i = 0; i < x.length; i ) {
//todo
}
It is recommended to change it to:
var html = [];
var x = document.getElementById("div");//Superior node
var node = x.firstChild;
while(node != null){
//todo
node = node.nextSibling;
}
JavaScript memory release
In web applications, as the number of DOM objects increases, memory consumption will become larger and larger. Therefore, the reference to the object should be released in time so that the browser can reclaim the memory.
Release the memory occupied by DOM
document.getElementById("test").innerHTML = "";
Set the innerHTML of a DOM element to an empty string to release the memory occupied by its child elements.
Release javascript object
//Object:
obj = null
//Object properties:
delete obj.property
//Array elements:
arr.splice(0,3);//Delete the first 3 elements

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
