JavaScript performance optimization Chapter JS optimization

Source: Internet
Author: User
Tags comments javascript array

I'll point out some important rules in this article about how you can use your JavaScript, what tools you use, and what benefits you'll get from it.


Make sure your code is as concise as possible

Don't rely on javascript for everything. Do not write repetitive scripts. To make JavaScript as a candy tool, it only plays a role in beautification. Don't add a lot of JavaScript code to your site. Use it only when necessary. Use it only when it does improve the user experience.

Minimizing DOM Access

Using JavaScript to access DOM elements is easy, the code is easier to read, but the speed is slow. Here are a few key points: restrict the use of JavaScript to decorate a page, and cache references to access elements. Sometimes, when your site relies on a lot of DOM changes, you should consider limiting your markup. This is a good reason to switch to HTML5 and discard the original XHTML and HTML4. You can view the number of DOM elements as long as you enter: document.getElementsByTagName (' * ') in the console of the Firebug plug-in. Length.

Compress code

The most effective way to provide a compressed JavaScript page is to compress your code with the JavaScript compression tool, which compresses variables and parameter names and then provides the resulting code, using gzip compression.

Yes, I did not compress my main.js, but you have to check for any jquery plugins that are uncompressed and don't forget to compress them. Here's a list of several scenarios for compression.

Yui compression Tools (my favorite, jquery development team to use it), Beginner's Guide (Http://www.slideshare.net/nzakas/ Extreme-javascript-compression-with-yui-compressor), second Guide (http://vilimpoc.org/research/js-speedup/) and official website (http:/ /developer.yahoo.com/yui/compressor/).

Dean Edwards Packer (http://dean.edwards.name/packer/)

Jsmin (Http://crockford.com/JavaScript/jsmin)

Gzip compression: The idea behind it is to shorten the time to transfer data between browsers and servers. After shortening the time, you get a file titled Accept-encoding:gzip,deflate. But there are some drawbacks to this compression method. It consumes processor resources (in order to compress and decompress) on both the server side and the client, and also takes up disk space.

Avoid eval (): Although Eval () sometimes brings some efficiency in terms of time, it is absolutely wrong to use it. Eval () causes your code to look dirtier and will escape the compression of most compression tools.

Tools to speed up JavaScript loading: lab.js

There are a number of great tools to speed up JavaScript loading. One of the tools worth mentioning is lab.js.

With lab.js (loading and blocking JavaScript), you can load JavaScript files in parallel, speeding up the overall loading process. In addition, you can set an order for the scripts that need to be loaded, which ensures the integrity of the dependencies. In addition, developers claim that the speed of their web site has increased twice times.

Using the appropriate CDN

Many web pages now use a Content distribution network (CDN). It can improve your caching mechanism because everyone can use it. It also saves you some bandwidth. You can easily use ping detection or use Firebug to debug those servers in order to figure out which aspects of the data will speed up. When choosing a CDN, take care of the location of the visitors to your site. Remember to use the common repository whenever possible.

Several CDN schemes for jquery:

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js--Google Ajax, for more information on the library see http://code.google.com/ Apis/libraries/devguide.html#libraries.

http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js--Microsoft's CDN

Http://code.jquery.com/jquery-1.4.2.min.js--Edgecast (MT).

To mount JavaScript at the end of a Web page


If you are concerned about the user, it is a good idea for the user not to leave your Web page because of the slow Internet connection. Ease of use and users in the first place, JavaScript at the bottom. This may be painful, but you should be prepared and some users will disable JavaScript. You can place some JavaScript that needs to be mounted in the header, but only if it is loaded asynchronously.

To mount the trace code asynchronously

This is very important. Most of us use the Google Analytics tool (Google Analytics) to get statistical data. This is good. Now take a look at where you put your tracking code. Is it in the head? Or does it use document.write? Then, if you don't use the Google Analytics tool to track code asynchronously, you can only blame yourself.

This is the way Google Analytics tools are tracking code asynchronously. We have to admit that it uses DOM instead of using document.write, which might be more suitable for you. It is important that you detect some of these events before the page is mounted. Now think about this situation, your page has not even mounted, all users have closed the page. You have found a way to resolve the missing page views.

 

The code is as follows Copy Code

var _gaq = _gaq | | [];

_gaq.push ([' _setaccount ', ' ua-xxxxxxx-xx ']);

_gaq.push ([' _trackpageview ']);

(function () {

var ga = document.createelement (' script '); Ga.type = ' Text/javascript '; Ga.async = true;

GA.SRC = (' https: ' = = Document.location.protocol? ' Https://ssl ': ' http://www ') + '. Google-analytics.com/ga.js ';

var s = document.getelementsbytagname (' script ') [0]; S.parentnode.insertbefore (GA, s);

})();

Not using Google Analytics tools? This is not a problem, and most of today's analytics tool providers allow you to use asynchronous tracing.

Ajax optimization

Ajax requests have a significant impact on the performance of your site. Here are some of the key points about Ajax optimization.

Caching your Ajax

Take a look at your code first. Can your AJAX cache? Yes, it relies on data, but most of your AJAX requests should be cached. In jquery, your request is cached by default, excluding the script and JSONP data types.

Use Get for AJAX requests

Post type requests that two TCP packets be sent (headers are sent first, then data is sent). Get type requests only need to send a packet (this may depend on the number of cookies you have). So, when your URL is less than 2K long, and you want to request some data, you might as well use get.

Using YSlow


language level aspects

Cycle
Loops are a very common control structure, most things depend on it to do it, in JavaScript we can use for (;;), while (), for (in) three loops, in fact, in these three loops for (in) is very inefficient because he needs to query the hash key, As long as you can, you should try to use less. for (;;) The performance of the while loop should be the same as the basic (usually used) equivalent.

In fact, the use of these two cycles, there is a great stress. I have some interesting situations in the test, see appendix. The final conclusion is:

If the loop variable is incremented or decremented, do not assign a value to the loop variable alone, and you should use the nested + + or--operator characters when it is last read.

If you want to compare the length of an array, you should put the length property of the array into a local variable in advance, reducing the number of queries.

For example, suppose Arr is an array, the best way to traverse the element is:

The code is as follows Copy Code

For (var i=0, len = arr.length;i<len;i++) {...} Or, if it doesn't matter in order:

for (Var i=arr.length;i>0;i--) {...} Local variables and global variables

Local variables are faster than global variables, because global variables are actually members of global objects, and local variables are placed in the stack of functions.

Do not use eval
using Eval is equivalent to invoking the interpretation engine to run the content at run time, which takes a lot of time. This time using JavaScript-supported closures enables functional templates (refer to functional programming for the contents of closures)

Reduce Object Lookup
because of the interpretation of JavaScript, so a.b.c.d.e, you need to do at least 4 query operations, first check A and then check a B, and then check C in B, so down. So if this expression repeats itself, as long as possible, you should try to minimize the expression, you can use the local variable, put it into a temporary place to query.

This can be combined with loops, because we often have to loop according to the length of the string, the length of the array, which is usually constant, such as the a.length of each query, the additional operation, and the advance of the Var
Len=a.length, there is one less query.

string concatenation
If you are appending a string, it is best to use the S+=ANOTHERSTR action instead of using S=S+ANOTHERSTR.

If you want to connect multiple strings, you should use + = less, such as

The code is as follows Copy Code

S+=a;s+=b;s+=c; should be written

The code is as follows Copy Code
S+=a + B + C;

If you are collecting strings, such as + + for the same string multiple times, it is best to use a cache. How to use it? Use a JavaScript array to collect, and then connect using the Join method, as follows

The code is as follows Copy Code
var buf = new Array (); for (var i = 0; i < i++) {Buf.push (i.tostring ());} var all = Buf.join ("");

Type conversions
type conversions are common mistakes, because JavaScript is a dynamic type language and you can't specify the type of variable.

1.
Convert numbers to strings, apply "+ 1", although it looks ugly, but in fact this efficiency is the highest, performance up to say:

The code is as follows Copy Code

("+" > String () >. toString () > New String ()

This is actually a bit like the "direct volume" below, where you can use an internal operation that you use at compile time faster than the user operation used at run time.

A string () is an intrinsic function, so it is very fast, and. ToString () to query the function in the prototype, so the speed is somewhat inferior, and the new String () is used to return an exact copy.

2.
Floating-point numbers are converted to integers, which is more prone to error, and many people prefer to use parseint (), in fact parseint () is used to convert strings to numbers rather than floating-point and integer conversions, and we should use Math.floor () or Math.Round ().

In addition, unlike the problem in the second section of the object lookup, math is an internal object, so Math.floor () actually does not have much of a query method and the time to call, the fastest speed.

3.
For custom objects, if the ToString () method is defined for type conversion, an explicit call to ToString () is recommended, because an internal operation attempts to convert the object's ToString () method to a string after attempting all possibilities. So it would be much more efficient to call this method directly.

Use Direct quantity
In fact, this effect is relatively small, can be ignored. What is called using the direct amount, for example, JavaScript supports using [Param,param,param,...] To express an array directly, we used to use the new array (Param,param,...), which is explained directly by the engine, which calls an array internal constructor, so a little bit faster.

Same

The code is as follows Copy Code
var foo = {} is also way more than var foo = new Object (), fast, var reg =/. /; faster than Var reg=new RegExp ().

String traversal operation
Looping strings, such as substitution and lookup, should use regular expressions, because JavaScript itself is slow to circulate, and regular expressions operate as APIs for languages written in C, and perform well.

Advanced objects
Custom Advanced objects and date, RegExp objects can consume a lot of time when they are constructed. If you can reuse, you should use the caching method.

Dom related
inserting HTML
Many people like to use document.write in JavaScript to generate content for a page. In fact, this is less efficient, if you need to insert HTML directly, you can find a container element, such as specifying a div or span, and set their innerhtml to insert their own HTML code into the page.

Object Query
using the ["] query is faster than. Items (), which is similar to the previous idea of reducing object lookup, and calling. Items () Adds a single call to the query and function.

Creating a DOM node
normally we might use strings to write HTML directly to create nodes, actually doing

Cannot guarantee the validity of the code

Low string operation efficiency

So you should use the Document.createelement () method, and if there are ready-made boilerplate nodes in the document, you should use the CloneNode () method, because after you use the createelement () method, you need to set the attributes of multiple elements. With CloneNode () you can reduce the number of times a property is set--and if you need to create many elements, you should prepare a boilerplate node first.

Timer
If you are working with code that is running, you should not use settimeout instead of setinterval. SetTimeout each time you want to reset a timer.

Other
Script engine
My test of Microsoft's JScript is much worse than Mozilla's SpiderMonkey, whether it's execution speed or memory management, because JScript is now basically not updated. But SpiderMonkey can't use ActiveXObject

File optimization
File optimization is also a very effective means to delete all the blanks and comments, put the code in a row, you can speed up the download speed, note that the speed of the download rather than the speed of resolution, if it is local, comments and spaces do not affect the interpretation and execution speed.

instance

The original code:

The code is as follows Copy Code
var s = [x1,x2,.....];
var t = [Y1,y2,.....].
The length of S and t corresponds, about 2,700 elements.
function String.prototype.s2c () {
var k= ';
for (Var i=0;i<this.length;i++)
k+= (S.indexof (This.charat (i)) ==-1) This.charat (i): T.charat (S.indexof (This.charat (i)))
return k;
}

This code is: replaces the character in string s with the character in the corresponding position in T. This method can be used on simplified conversions. The length of a string is not small, generally the length of a blog post.

First optimization: Turn K into an array, because the string addition is not array.join memory efficiency is good.

The code is as follows Copy Code
function String.prototype.s2c () {
var k=[];
for (Var i=0;i<this.length;i++)
K.push ((S.indexof (This.charat (i)) ==-1) This.charat (i): T.charat (S.indexof (This.charat (i))));
Return K.join (");
}

Efficiency is improved a lot.

Second optimization: Reduces the number of operations within a loop.

The code is as follows Copy Code
function String.prototype.s2c () {
var k=[];
for (Var i=0;i<this.length;i++) {
var Thisc = This.charat (i);
K.push (S.indexof (THISC) ==-1) Thisc:t.charat (S.indexof (Thisc)));
}
Return K.join (");
}

This time the three this.charat (i) call into a call, the efficiency is also improved.

Third optimization: Change the indexof of the array into HashMap lookup way, modify the this.length inside the loop
Create HashMap First:

The code is as follows Copy Code
var sMap = {},tmap={};
for (Var i=0;i<s.length;i++) {
var Schar = S.charat (i);
var TChar = T.charat (i);
Smap[schar] = TChar;
Tmap[tchar] = Schar;
}

Then modify the code:

The code is as follows Copy Code
function String.prototype.s2c () {
var k=[];
var len = this.length;
for (Var i=0;i<len;i++) {
var Thisc = This.charat (i);
K[i] = Smap[thisc] | | Thisc;
}
Return K.join (");
}

This time improve performance will also have a better upgrade.

Last optimization: Improves array access performance.
Split the original string into groups and then operate on an array.

The code is as follows Copy Code

function String.prototype.s2c () {
var len = this.length;
var k=this.split (');
for (Var i=0;i<len;i++) {
var thisc = this[i];
var to = SMap (THISC);
To?k[i]=to: '; Here's a little trick, which leads to less assignment operations when there is no thisc mapping in SMAP.
}
Return K.join (");
}

Some of the techniques found in JavaScript programming to improve the performance of JavaScript are based on several principles:

It's quicker to take things that are readily available, such as local variables that are faster than global variables, and the direct amount is faster than the Run-time construction object, and so on.

Reduce the number of executions as little as possible, such as caching requires multiple queries.

Use language-built-in features, such as String links, whenever possible.

Use the API provided by the system whenever possible, because these APIs are compiled binary code that is highly efficient

At the same time, some basic algorithms for optimization, also can be used in JavaScript, such as the adjustment of the structure of the operation, here is no longer repeat. However, since JavaScript is interpreted and generally does not optimize bytecode at run time, these optimizations are still important.

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.