Summary of methods for optimizing JavaScript code

Source: Internet
Author: User
ArticleDirectory
    • Avoid browser memory leakage

Optimize JavascriptCode
Author: Gregory Baker, Gmail software engineer and Erik Arvidsson, Google Chrome software engineer
Experience required: knowledge about Javascript
Client scripts allow your applications to be more dynamic and active, but the browser may cause efficiency problems in code parsing, and this performance difference varies across clients. here we will discuss and provide some tips and best practices for optimizing your JavaScript code.
Use string
The string connection 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, the string is connected to IE8 and other non-ie browsers (such as chrome) A little more efficient-if a large part of your users are using Internet Explorer 6 or 7, you need to pay attention to the way you build strings.
The following sample code is provided:

Copy code Code: 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 shoshould we do the wrapping? ';

Try to use join () instead of join ():Copy codeCode: var verylongmessage =
['This is a long string that due to our strict line length limit ',
Maxcharsperline,
'Characters per line must be wrapped .',
Percentwhodislike,
'% Of engineers dislike this rule. The line length limit is ',
'Style purposes, but we don't want it to have a performance impact .',
So the question is how shoshould we do the wrapping? '
]. Join ();

Similarly, it is inefficient to construct strings in conditional statements and loops using the join method. The error method is as follows:Copy codeThe Code is as follows: var fibonaccistr = 'first 20 Fibonacci number ';
For (VAR I = 0; I <20; I ++ ){
Fibonaccistr + = I + '=' + Fibonacci (I) +'
';
}

The correct method: Copy codeThe Code is as follows: var strbuilder = ['first 20 Fibonacci numbers: '];
For (VAR I = 0; I <20; I ++ ){
Strbuilder. Push (I, '=', FIG (I ));
}
VaR fibonaccistr = strbuilder. Join ('');

Construct a string generated by the Auxiliary Function
Create a long string by passing the string Builder (which can be an array or helper class) to the function to avoid the string that stores the temporary results.
For example, assume that buildmenuitemhtml _ needs to construct a string with a text string and a variable, and uses a character string builder internally, instead:Copy codeThe Code is as follows: var strbuilder = [];
For (VAR I = 0; I <menuitems. length; I ++ ){
Strbuilder. Push (this. buildmenuitemhtml _ (menuitems [I]);
}
VaR menuhtml = strbuilder. Join ();

Better use:Copy codeThe Code is as follows: var strbuilder = [];
For (VAR I = 0; I <menuitems. length; I ++ ){
This. buildmenuitem _ (menuitems [I], strbuilder );
}
VaR menuhtml = strbuilder. Join ();

Define the Class Method
The following code is inefficient because every time you construct an instance of Baz. Bar, a new function and closure (closure) will be created for FOO ):Copy codeThe Code is as follows: Baz. bar = function (){
// Constructor code
This. Foo = function (){
// Method code
};
}

Recommended Methods: Copy codeThe 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 is created for foo and no closure is created.
Initialize instance variables
Initialize the value with a value type (non-referenced) (for example, the type is numeric, Boolean, null, undefined, or string value) the variable Declaration/initialization code is directly stored in the prototype. this avoids unnecessary initialization code execution every time you call the constructor. (this method cannot be applied to instance variables whose initial values are determined by the constructor parameters or whose status is not certain during the constructor .)
For example, compared to writing:Copy codeThe Code is as follows: Foo. bar = function (){
This. prop1 _ = 4;
This. prop2 _ = true;
This. prop3 _ = [];
This. prop4 _ = 'blah ';
};

Write as follows:Copy codeThe 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 in Javascript; however, they also have disadvantages, including:
These are the most common sources of Memory leakage.
Creating a closure is obviously slower than creating an inline function without a closure, and slower than reusing a static function. For example:Copy codeThe Code is as follows: function setupalerttimeout (){
VaR MSG = 'message to be displayed ';
Window. setTimeout (function () {alert (MSG) ;},100 );
}

It is slower than the following code:Copy codeThe Code is as follows: function setupalerttimeout (){
Window. setTimeout (function (){
VaR MSG = 'message to be displayed ';
Alert (MSG );
},100 );
}

It is slower than the following code:Copy codeThe Code is as follows: function alertmsg (){
VaR MSG = 'message to be displayed ';
Alert (MSG );
}
Function setupalerttimeout (){
Window. setTimeout (alertmsg, 100 );
}

They added the scope chain level. When the browser parses attributes, each level of the scope chain must be checked once. In the following example:Copy codeThe 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, referencing a is slower than referencing B. They are slower than referencing C.

View ie + JScript performance recommendations Part 3: JavaScript code inefficiencies for more information about using closures in IE.

Avoid using With

Avoid usingWithIt has a very bad impact on performance, because it modifies the scope chain, making it expensive to search for variables in other scopes.

Avoid browser memory leakage

Memory leakage is a common problem for Web applications, which may cause serious performance problems. when the browser memory usage increases, your web applications, along with other parts of the user system, will become slower. the most common cause of Memory leakage for Web applications is the circular reference between the Javascript script engine and the C ++ object Implementation of the browser dom (for example, between the Javascript script engine and Internet Explorer's com infrastructure, or between the JavaScript engine and Firefox's XPCOM infrastructure ).

The following are some empirical rules to avoid Memory leakage:

Use an Event System to attach event processing functions

The most common circular reference mode [Dom element --> Event Handler --> closure scope --> Dom] has been discussed in this blog article on msdn. to avoid this problem, you can use a strictly tested Event System to attach event processing functions, such as Google doctype, dojo, or jquery.

In addition, using inline event processing functions in IE will lead to another type of leakage. this is not the usual loop reference leakage, but the leakage of temporary anonymous Script objects in the memory. for more information, see section "dom Insertion Sequence Leakage Model (DOM insertion order leak model)" in understanding and solving the understanding and solving Internet Explorer leak patterns, in addition, there is an example in the Javascript kit tutorial.

Avoid using extended (expando) attributes

extended attributes are arbitrary Javascript attributes appended to DOM elements and are common causes of circular references. you can use the extended attributes without causing memory leakage, but it is easy to introduce a leak accidentally. this mode of leakage is [DOM elements --> extended attributes --> intermediate objects --> DOM elements]. the best way is to avoid using them. if you want to use them, only simple value types are used. if you want a non-simple type, set it to null when you no longer need to extend the attribute ). for more information, see "circular references" in the understanding and solving Internet Explorer leak patterns.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.