Summarize some functions and statements to avoid using in JavaScript
Avoid using eval or Function constructor
Using eval or Function constructor is very expensive and requires the script engine to convert the source code every time to executable code.
In addition, using eval to process strings must be interpreted at runtime.
Code that runs slowly:
function addMethod(object, property, code) {
object[property] = new Function(code);
}
addMethod(myObj, 'methodName', 'this.localVar=foo');Code that runs faster:
function addMethod(object, property, func) {
object[property] = func;
}
addMethod(myObj, 'methodName', function () { 'this.localVar=foo'; });
Avoid using with
Although it is convenient, with requires additional reference search time because it does not know the upper and lower scopes at compile time.
Code that runs slowly:
with (test.object) {
foo = 'Value of foo property of object';
bar = 'Value of bar property of object';
} Code that runs faster:
var myObj = test.object; myObj.foo = 'Value of foo property of object'; myObj.bar = 'Value of bar property of object';
Do not use try-catch-finally in functions with critical performance requirements
try-catch-finally will create a new variable in the current scope each time during runtime, use Exception in execution of allocation statement.
Exception handling should be done at a high level in the script, where exceptions do not occur very frequently, such as outside a loop.
If possible, try to avoid using try-catch-finally entirely.
Code that runs slowly:
var object = ['foo', 'bar'], i;
for (i = 0; i < object.length; i++) {
try {
// do something that throws an exception
} catch (e) {
// handle exception
}
}Code that runs faster:
var object = ['foo', 'bar'], i;
try {
for (i = 0; i < object.length; i++) {
// do something
}
} catch (e) {
// handle exception
}
Avoid using global variables
If you are When global variables are used in a function or other scope, the script engine needs to traverse the entire scope to find them.
Variables in the global scope exist throughout the life cycle of the script, and those in the local scope will be destroyed when the local scope is lost.
Code that runs slowly:
var i,
str = '';
function globalScope() {
for (i=0; i < 100; i++) {
str += i; // here we reference i and str in global scope which is slow
}
}
globalScope();Code that runs faster:
function localScope() {
var i,
str = '';
for (i=0; i < 100; i++) {
str += i; // i and str in local scope which is faster
}
}
localScope();
Avoid functions that are critical to performance requirements Using for-in
The for-in loop requires the script engine to build a list of all enumerable properties and check whether they are duplicates of the previous ones.
If the code in your for loop scope does not modify the array, you can pre-calculate the length of the array and use it to iterate the array in the for loop.
Code that runs slowly:
var sum = 0;
for (var i in arr) {
sum += arr[i];
}Code that runs faster:
var sum = 0;
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i];
}The above is the detailed content of Summarize some functions and statements to avoid using in JavaScript. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
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
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
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems
Dec 17, 2023 pm 05:30 PM
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
Recommended: Excellent JS open source face detection and recognition project
Apr 03, 2024 am 11:55 AM
Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side
How to implement an online speech recognition system using WebSocket and JavaScript
Dec 17, 2023 pm 02:54 PM
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.
Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS
Dec 17, 2023 pm 06:55 PM
Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price
How to use JavaScript and WebSocket to implement a real-time online ordering system
Dec 17, 2023 pm 12:09 PM
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
Which computer should Geographic Information Science majors choose?
Jan 13, 2024 am 08:00 AM
Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.
JavaScript and WebSocket: Building an efficient real-time weather forecasting system
Dec 17, 2023 pm 05:13 PM
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
Simple JavaScript Tutorial: How to Get HTTP Status Code
Jan 05, 2024 pm 06:08 PM
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


