search
HomeWeb Front-endJS TutorialSummary of JavaScript performance traps (with examples)_javascript skills

1. Avoid using eval or Function constructor
2. Avoid using with
3. Do not use try-catch-finally in functions with critical performance requirements
4. Avoid using global variables
5. Avoid using for-in in functions with critical performance requirements
6. Use string accumulation calculation style
7. The original operation will be faster than the function call
8. Pass when setting setTimeout() and setInterval() Function names instead of strings
9. Avoid using unnecessary DOM references in objects
10. Clearest target speed, minimize scope chain
11. Try to use fewer comments in scripts , avoid using long variable names
12. Store external variables of the application in the current scope
13. Use variables to cache values ​​

1. Avoid using eval or Function constructors
Using eval or Function constructors is very expensive, requiring a script engine to convert source code to executable code every time.
Additionally, using eval to handle strings must be interpreted at runtime.

Code that runs slowly:

Copy the code The code is as follows:

function addMethod(object, property, code) {
object[property] = new Function(code);
}
addMethod(myObj, 'methodName', 'this.localVar=foo');

Code that runs faster:
Copy the code The code is as follows:

function addMethod(object, property, func) {
object[property] = func;
}
addMethod(myObj, 'methodName', function () { 'this.localVar=foo'; });

2. Avoid using with
Although very convenient, with requires additional search reference time because it does not know the upper and lower scope at compile time.

Code that runs slowly:
Copy the code The code is as follows:

with (test.object) {
foo = 'Value of foo property of object';
bar = 'Value of bar property of object';
}

runs faster Code:
Copy code The code is as follows:

var myObj = test.object;
myObj.foo = 'Value of foo property of object';
myObj.bar = 'Value of bar property of object'; Use try-catch-finally in a function
try-catch-finally will create a new variable in the current scope each time during runtime, which is used to allocate exceptions in statement execution.
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:




Copy code
The code is as follows: var object = ['foo', 'bar'], i; for (i = 0; i try {
// do something that throws an exception
} catch (e) {
// handle exception
}
}


Run faster code:



Copy code
The code is as follows: var object = ['foo', 'bar'], i; try {
for (i = 0; i // do something
}
} catch (e) {
// handle exception
}



4. Avoid using global variables
If you use global variables 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:




Copy code
The code is as follows: var i, str = '';
function globalScope() {
for (i=0; i str = i; // here we reference i and str in global scope which is slow
}
}
globalScope();


Code that runs faster:
Copy code The code is as follows:

function localScope( ) {
var i,
str = '';
for (i=0; i str = i; // i and str in local scope which is faster
}
}
localScope();

5. Avoid using for-in
for- in functions with critical performance requirements The in loop requires the script engine to build a list of all enumerable properties and check if 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:
Copy code The code is as follows:

var sum = 0;
for (var i in arr) {
sum = arr[i];
}

Run faster code:
Copy code The code is as follows:

var sum = 0;
for (var i = 0, len = arr .length; i sum = arr[i];
}

6. Use string accumulation calculation style
Using an operation creates a new string in memory and assigns the concatenated value to it. Just assign the result to a variable.
In order to avoid connecting the intermediate variables of the result, you can use = to directly assign the result.

Code that runs slowly:
Copy code The code is as follows:

a = 'x' 'y';

Run faster code:
Copy code Code As follows:

a = 'x'; a = 'y';

7. The original operation will be faster than the function call
Consider using alternative primitive operations in loops and functions where performance is critical.
Code that runs slowly:
Copy code The code is as follows:

var min = Math .min(a, b);
arr.push(val);

Run faster code:
Copy code The code is as follows:

var min = a arr[arr.length] = val;

8. When setting setTimeout() and setInterval(), pass the function name instead of a string
If you pass a string to setTimeout() or setInterval(), the string will It will be calculated by eval and cause slowness.
Use an anonymous function wrapper instead so it can be interpreted and optimized at compile time.

Code that runs slowly:
setInterval('doSomethingPeriodically()', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000);

Code that runs faster :
Copy code The code is as follows:

setInterval(doSomethingPeriodically, 1000);
setTimeOut (doSomethingAfterFiveSeconds, 5000);

9. Avoid using unnecessary DOM references in objects

Don’t do this:

Copy code The code is as follows:

var car = new Object();
car.color = " red";
car.type = "sedan"

A better form:

Copy code The code is as follows:

var car = {
color : "red";
type : "sedan"
}

10. Clearest target speed, minimize scope chain

Inefficient method:
Copy code The code is as follows:

var url = location.href;

An efficient form:
Copy code The code is as follows:

var url = window.location.href;

11. Try to use less comments in the script and avoid using long Variable names
should have as few comments as possible or avoid using them, especially in functions, loops and arrays.
Comments unnecessarily slow down script execution and increase file size. For example:

Not recommended form:

Copy code The code is as follows:

function someFunction()
{
var person_full_name="somename"; /* stores the full name*/
}

Better way of writing:
Copy code The code is as follows:

function someFunction()
{
var name= "somename";
}

12. Store the external variables of the application in the current scope
When a function is executed, the running context is passed, An active object will contain all local variables that will be pushed to the front of the context chain.
In the scope chain, the slowest ones are clearly identified identifiers, meaning local variables are the fastest. Reading and writing frequently used external variables will be significantly faster. This is especially noticeable for global variables and other deep identifier lookups.
Similarly, variables in the current scope (var myVar) are accessed faster than objects like properties (this.myVar).

Slow-running code:

Copy the code The code is as follows:

function doSomething(text) {
var divs = document.getElementsByTagName('div'),
text = ['foo', /* ... n ... */, 'bar'];
for (var i = 0, l = divs.length; i divs[i].innerHTML = text[i];
}
}

Code that runs faster:

Copy the code The code is as follows:

function doSomethingFaster(text) {
var doc = document,
divs = doc.getElementsByTagName('div'),
text = ['foo', /* ... n ... */, 'bar'];
for (var i = 0, l = divs.length; i divs[i].innerHTML = text[i];
}
}

If you need to access an element (such as head) in a large loop, it will be faster to use a local DOM access (such as get in the example).
Code that runs faster:
Copy code The code is as follows:

function doSomethingElseFaster( ) {
var get = document.getElementsByTagName;
for (var i = 0, i get('head');
}
}

13. Use variables to cache values ​​
Use local variables to cache values ​​where repeated work is done.
The following set of examples illustrates the broad implications of storing values ​​into local variables.

Example 1. Use variables to store mathematical functions in the loop body before calculation execution
Wrong method:
Copy code The code is as follows:

var d=35;
for (var i=0; iy = Math.sin(d)*10 ;
}

Better processing:
Copy code The code is as follows:

var d = 55;
var math_sind = Math.sin(d)*10;
for (var i=0; iy = math_sind ;
}

Example 2. Saving the length of the array using
in a loop. Poor processing:
The length of the array will be recalculated every time
Copy code The code is as follows:

for (var i = 0; i // do something
}

Better improvement:
A better way is to save the length of the array
Copy the code The code is as follows:

for (var i = 0, len = arr.length; i // do something
}

Total Generally speaking, if it has been done once, we do not need to do unnecessary work repeatedly. For example, if the value of a calculated expression is used multiple times in a scope or function, saving it to a variable allows it to be used multiple times, otherwise we would overdo it by declaring a variable and assigning it a value that only applies once. So please keep these in mind.

Additional explanation:
Point 2
By the way, JS is not compiled but interpreted. Although it does not affect expression, it is better to be academically rigorous.

Point 6: Is this a messed up format?
a = 'x' 'y';
Run faster code:

a = 'x'; a = 'y';

9. Avoid using unnecessary DOM references in objects
Is new Object also a DOM reference?
This should mean that you should not use new Object() and new Array lightly. (), and new Function() generally use {...}, [...], f = function(..){...}, that is:
This should be the same as the above point. That's it.

Finally, I would like to add that you should use less bit operations, because all numerical operations in js (at the JS engine level) are all converted to floating point calculations... so bit operations may be slower. .
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Syntax Highlighters10 jQuery Syntax HighlightersMar 02, 2025 am 12:32 AM

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

10  JavaScript & jQuery MVC Tutorials10 JavaScript & jQuery MVC TutorialsMar 02, 2025 am 01:16 AM

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!