Suggestions for optimizing JavaScript code

Source: Internet
Author: User

Client scripts make the application more attractive, but the execution of the browser's interpretation of the script code may also lead to low efficiency.

Here we will discuss several best practices and suggestions for optimizing JavaScript code.

 

1. Process strings

The garbage collection performance of String concatenation in IE 6 and 7 is poor. Although IE 8 has solved this problem. If a considerable number of your users use IE 6 and 7, you have to be careful when constructing your string.

For example:

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?';

Do not directly use String concatenation +. A better way is to use join:

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, String concatenation is inefficient in condition branch statements or loop statements. Bad practices:

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

Correct practice:

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

2. Use helper functions to construct string fragments

You can pass the string builder into the Helper function to avoid temporary storage consumption.

For example, you should not use the following:

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

Instead, use:

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

 

3. Define class methods

The following code is inefficient because every time a Baz. Bar instance is created, a new function and closure are created for FOO:

baz.Bar = function() {  // constructor body  this.foo = function() {  // method body  };}

The best practice is:

baz.Bar = function() {  // constructor body};baz.Bar.prototype.foo = function() {  // method body};

In this way, no matter how many Baz. Bar instances are created, only one function is created and no closure is formed.

 

4. initialize instance variables

Put the instance variable Declaration/initialization into prototype if the instance variable has an initial value of the value type (number, Boolean, null, undefined, or string type value ). This avoids running meaningless initialization code every time the constructor is created.

Bad practices:

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

Better Practices:

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

 

5. Avoid traps in closures

Closures are powerful and useful. However, they have some disadvantages, including:

1. They are the major culprit of Memory leakage 2. It is slower to create a closure than to create an inline function, and the proportion of a static function is slower.

For example:

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

It is slower than the following code:

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

The above code is slower than the following code:

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

The closure adds a scope chain. When the browser parses properties, the scope chain of each layer must be checked. In the following example:

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

When F is called, referencing a is slower than referencing B, and referencing B is slower than referencing C.

View ie + JScript performance recommendations Part 3: JavaScript code inefficiencies to get more information on correct closure use in IE

 

6. Avoid

Avoid using the with statement in the code. It has a negative impact on performance because it changes the scope chain, making it more expensive to search for variables in other scopes.

 

7. Avoid browser memory leakage

Memory leakage is a common problem in web applications and may cause huge performance problems. When the memory consumed by the browser increases, your other web applications and other programs in the user system will become very slow. The most common memory leakage scenario is the circular dependency between the JavaScript engine and the browser's DOM objects. For example, the following example:

<script language='javascript'>   var menu = document.getElementById('myMenu');   AttachEvent(menu);   function AttachEvent(element) {      element.attachEvent( "onmouseover", mouseHandler);      function mouseHandler(){ /* whatever */ }   }</script>
Another example is the following code:
var myGlobalObject;function SetupLeak(){   //Here a reference created from the JS World     //to the DOM world.    myGlobalObject=document.getElementById("LeakedDiv");    //Here DOM refers back to JS World;     //hence a circular reference.    //The memory will leak if not handled properly.    document.getElementById("LeakedDiv").expandoProperty = myGlobalObject;}
For more information, see: http://www.javascriptkit.com/javatutors/closuresleak/index.shtml
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.