Home > Web Front-end > JS Tutorial > body text

Summary of methods to optimize JavaScript code_javascript skills

WBOY
Release: 2016-05-16 18:49:51
Original
1115 people have browsed it

Optimizing JavaScript Code
Author: Gregory Baker, GMail Software Engineer and Erik Arvidsson, Google Chrome Software Engineer
Required experience: Working knowledge of JavaScript
Client-side scripting can make your application more dynamic and active, but browser parsing of the code may cause efficiency issues, and this performance difference varies between clients. Here we discuss and give some tips and best practices for optimizing your JavaScript code.
Using Strings
The string concatenation operation will have a great impact on the garbage collection of Internet Explorer 6 and 7. Although this problem is solved in Internet Explorer 8 - String Concatenation Slightly more efficient in IE8 and other non-IE browsers (such as Chrome) - if a large proportion of your users are using Internet Explorer 6 or 7, you need to be very careful about how you build strings.
There is the following sample code:

Copy code The code is as follows:

var veryLongMessage =
'This is a long string that due to our strict line length limit of'
maxCharsPerLine
' characters per line must be wrapped. '
percentWhoDislike
'% of engineers dislike this rule. The line length limit is for '
' style purposes, but we don't want it to have a performance impact.'
' So the question is how should we do the wrapping?';

Instead of using join method, try using join():
Copy the code The code is as follows:

var veryLongMessage =
['This is a long string that due to our strict line length limit of',
maxCharsPerLine,
' characters per line must be wrapped. ',
percentWhoDislike,
'% of engineers dislike this rule. The line length limit is for ',
' style purposes, but we don't want it to have a performance impact.',
' So the question is how should we do the wrapping?'
].join();

Similarly, concatenating strings in conditionals and loops is inefficient. Wrong way :
Copy code The code is as follows:

var fibonacciStr = 'First 20 Fibonacci Number';
for (var i = 0; i < 20; i ) {
fibonacciStr = i ' = ' fibonacci(i) '
';
}

Correct method:
Copy code The code is as follows:

var strBuilder = ['First 20 Fibonacci numbers:'];
for (var i = 0; i < 20; i ) {
strBuilder.push(i, ' = ', fibonacci (i));
}
var fibonacciStr = strBuilder.join('');

Construct the string generated by the helper function
Pass Pass a string builder (can be an array or a helper class) to the function to build long strings to avoid strings holding temporary results.
For example, suppose buildMenuItemHtml_ needs to build a string from literal strings and variables, and A string builder is used internally, instead of using:
Copy code The code is as follows:

var strBuilder = [];
for (var i = 0; i < menuItems.length; i ) {
strBuilder.push(this.buildMenuItemHtml_(menuItems[i]));
}
var menuHtml = strBuilder.join();

Instead of using:
Copy code Code As follows:

var strBuilder = [];
for (var i = 0; i < menuItems.length; i ) {
this.buildMenuItem_(menuItems[i], strBuilder ; When constructing an instance of baz.Bar, a new function and closure will be created for foo:



Copy code
The code is as follows :

The recommended way is:
Copy the code The code is as follows:

baz.Bar = function() {
// Constructor code
};
baz.Bar.prototype.foo = function() {
// Method code
};

In this way, no matter how many baz.Bar instances are constructed, only one function will be created for foo, and no closure will be created.
Initializing the instance variables
will Place variable declaration/initialization code with initialization values ​​of value types (non-reference) directly in the prototype prototype. This avoids calling the constructor every time Function to run initialization code unnecessarily. (This approach cannot be applied to instance variables whose initialization values ​​are determined by constructor parameters or whose state is uncertain at construction time.)
For example, instead of writing:
Copy code The code is as follows:

foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};

Why not write:
Copy code The code is as follows:

foo.Bar = function() {
this.prop3_ = [] ;
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';

Use closures with caution
Closures are a powerful and useful feature of JavaScript; however, they also have downsides, including:
They is the most common source of memory leaks.
Creating a closure is significantly slower than creating an inline function without a closure, and even slower than reusing a static function. For example:
Copy code The code is as follows:

function setupAlertTimeout() {
var msg = 'Message to be displayed';
window.setTimeout(function() { alert(msg); }, 100);
}

is slower than the following code:
Copy code The code is as follows:

function setupAlertTimeout() {
window.setTimeout(function() {
var msg = 'To display message';
alert(msg);
}, 100);
}

is even slower than the following code:
Copy code The code is as follows:

function alertMsg() {
var msg = 'Message to be displayed';
alert (msg);
}
function setupAlertTimeout() {
window.setTimeout(alertMsg, 100);
}

They added scope chain ) levels. When the browser parses the attribute, each level of the scope chain must be checked once. In the following example:
Copy code The code is as follows:

var a = 'a';
function createFunctionWithClosure() {
var b = 'b';
return function () {
var c = 'c';
a;

c;
};
}
var f = createFunctionWithClosure();
f();

When f is called, reference a is slower than reference b, and they are both slower than reference c.

Check out IE JScript Performance Recommendations Part 3: JavaScript Code inefficiencies for more information on using closures in IE.

Avoid using <SPAN style="COLOR: #336600">with</SPAN>

Avoid using in your code<SPAN style="COLOR: #336600">with</SPAN>. It has a very bad impact on performance because it modifies the scope chain, making it expensive to look up variables in other scopes.

Avoid browser memory leaks

Memory leaks are a very common problem for web applications, and they can cause serious performance problems. When the browser's memory usage increases, your web application, along with the rest of the user's system, will slow down. The most common causes of memory leaks in web applications are: circular references between the JavaScript engine and the browser DOM's C object implementation (for example, between the JavaScript engine and Internet Explorer's COM infrastructure, or between the JavaScript engine and Firefox's XPCOM infrastructure Architectural room).

Here are some rules of thumb to avoid memory leaks:

Use an event system to attach event handlers

The most common circular reference pattern [DOM element--> event handler--> closure scope--> DOM] is in this article MSDN Discussed in the blog article. To avoid this problem, you can use a well-tested event system to attach event handlers, such as Google doctype, Dojo , or JQuery.

In addition, using inline event handlers in IE will cause another type of leak. This is not a usual circular reference leak, but a leak of temporary anonymous script objects in memory. Please see for details Understanding and Solving Internet Explorer Leak Patterns 's "DOM Insertion Order Leak Model" section, also in There is also an example in the JavaScript Kit tutorial.

Avoid using expando attributes

Extended attributes are arbitrary JavaScript attributes attached to DOM elements and are a common cause of circular references. You can use extended attributes without causing a memory leak, but it is easy to accidentally introduce a leak. The pattern of this leak is [DOM Element--> Extended Attributes--> Intermediate Object--> DOM Element]. The best way is to avoid using them. If you are going to use them, just use simple value types. If you are going to use Simple type, then set the extended attribute to null when it is no longer needed. See Understanding and Solving Internet Explorer Leak Patterns "Circular References" section.

Related labels:
source:php.cn
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
Popular Tutorials
More>
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!