Excerpt: JavaScript performance Optimization Trivia Summary

Source: Internet
Author: User
Tags event listener instance method javascript array

Original address: http://www.codeceo.com/article/javascript-performance-tips.html

JavaScript performance issues are not to be underestimated, this requires our developers to write JavaScript program more attention to some details, this article is a very detailed introduction of JavaScript performance optimization of knowledge points, is definitely dry. Objective

have been learning JavaScript, but also have seen the "sharp development of the jquery core of the detailed and practice," The book evaluation only two sharp words, may be not enough to understand the JavaScript is not clear or too stupid, More is not good at thinking too lazy to think so that some of the essence is not too deep understanding.

In view of want to let oneself have a promotion, cannot enter a broader world, must find a own residence to live well, so usually will consciously or unconsciously to accumulate some use jquerry common knowledge, especially for performance requirements this piece, always will think is not a better way to achieve.

Here are some tips I've summed up, for reference only. (I'll start by saying a headline and then use a short paragraph to illustrate the meaning and then use a demo to make it simple) avoid global lookups

Global objects are stored as local variables in a function to reduce global lookups, because accessing local variables is faster than accessing global variables.

        function Search () {            //When I want to use the current page address and host Domain            alert (window.location.href + window.location.host);        }        The best way to do this is to  save the        function search () {            var location = window.location            with a simple variable first): Alert (location.href + location.host);        }
Timer

If you are targeting code that is constantly running, you should not use settimeout, but shouldbe using setinterval, because settimeout Initializes a timer every time, and setinterval Initializes a timer at the beginning.

        var timeouttimes = 0;        function timeout () {            timeouttimes++;            if (Timeouttimes <) {                setTimeout (timeout, ten);}        }        Timeout ();        Can be replaced by:        var intervaltimes = 0;        function interval () {            intervaltimes++;            if (Intervaltimes >=) {                clearinterval (interv);            }        }        var interv = setinterval (interval, 10);
String connection

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

S+=a;

S+=b;

S+=c;

should be written s+=a + B + C;

If you are collecting strings, such as multiple + = operations on the same string, it is best to use a cache, use a JavaScript array to collect, and finally join using the Join method .

        var buf = [];        for (var i = 0; i < i++) {            Buf.push (i.tostring ());        }        var all = Buf.join ("");
Avoid with statements

Like functions, the WITH statement creates its own scope, which increases the length of the scope chain in which the code executes, and because of the additional scope chain lookup, the code executed in the WITH statement is certainly slower than the code executed outside the Try not to use the WITH statement without using the WITH statement .

With (a.b.c.d) {            property1 = 1;            Property2 = 2;        }        Can be replaced by:        var obj = a.b.c.d;        Obj.property1 = 1;        Obj.property2 = 2;
Convert numbers to Strings

It is best to use the "" + to convert a number to a string, although it looks uglier, but in fact the efficiency is the highest, performance says:

("" +) > string () >. toString () > New String ( ) floating-point number converted to integral type

Many people like to use parseint (), in fact parseint () is used to convert a string into a number instead of a floating-point and integer conversion between, we should use Math.floor () or Math.Round () various types of conversion

var MyVar = "3.14159",        str = "" "+ MyVar,//To  string          I_int = ~ ~myvar,  //To  integer          f_float = 1 * MyVar,  //to  float          B_bool =!! MyVar,/* to Boolean-any string with length and any number                                 except 0 is true */        array = [myvar];
   
    //to  Array
   

If the ToString () method is defined for type conversion, it is recommended that you explicitly call ToString (), because the internal operation attempts to convert the ToString () method of the object to a string after attempting all possibilities. So it's more efficient to call this method directly. More than one type declaration

All variables in JavaScript can be declared using a single VAR statement, which is a combination of statements to reduce the execution time of the entire script, as in the above code, the code format is also very normative, let a person look at the clear. Inserting iterators

such as Var name=values[i]; i++; The preceding two statements can be written as Var name=values[i++] use Direct volume

var atest = new Array (); Replace with        var atest = [];        var atest = new Object; Replace with        var atest = {};        var reg = new RegExp (); Replace with        var reg =/: /;        If you want to create a generic object with some attributes, you can also use the literal, as follows:        var ofruit = new O;        Ofruit.color = "Red";        Ofruit.name = "Apple";        The preceding code can be rewritten with the object literal:        var ofruit = {color: "Red", Name: "Apple"};
Optimize multiple Append with documentfragment

Once you need to update the DOM, consider using document fragmentation to build the DOM structure and then add it to the existing document.

for (var i = 0; i < i++) {            var el = document.createelement (' P ');            el.innerhtml = i;            Document.body.appendChild (EL);        }        Can be replaced by:        var frag = document.createdocumentfragment ();        for (var i = 0; i < i++) {            var el = document.createelement (' P ');            el.innerhtml = i;            Frag.appendchild (EL);        }        Document.body.appendChild (Frag);
Use a innerhtml assignment instead of building DOM elements

For large DOM changes, it is much faster to use innerhtml than to create the same DOM structure using standard DOM methods.

        var frag = Document.createdocumentfragment ();        for (var i = 0; i < i++) {            var el = document.createelement (' P ');            el.innerhtml = i;            Frag.appendchild (EL);        }        Document.body.appendChild (Frag);        Can be replaced by:        var html = [];        for (var i = 0; i < i++) {            html.push (' <p> ' + i + ' </p> ');        }        Document.body.innerHTML = Html.join (");
Replace createelement with template element clone

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. Usually we may use the string to write the HTML directly to create the node, in fact, 1 can not guarantee the validity of the code 2 string operation is inefficient, so should be using the Document.createelement () method, and if there is a ready-made template node in the document, should be using the CloneNode () method, because after using the createelement () method, you need to set the properties of multiple elements, using clonenode () can reduce the set number of properties-also if you need to create many elements, you should first prepare a template node

        var frag = Document.createdocumentfragment ();        for (var i = 0; i < i++) {            var el = document.createelement (' P ');            el.innerhtml = i;            Frag.appendchild (EL);        }        Document.body.appendChild (Frag);        To be replaced by:        var frag = document.createdocumentfragment ();        var pEl = document.getelementsbytagname (' P ') [0];        for (var i = 0; i < i++) {            var el = Pel.clonenode (false);            el.innerhtml = i;            Frag.appendchild (EL);        }        Document.body.appendChild (Frag);
Traversing DOM elements using FirstChild and nextsibling instead of childnodes

        var nodes = Element.childnodes;        for (var i = 0, L = nodes.length; i < L; i++) {            var node = nodes[i];            ...        }        Can be replaced by:        var node = element.firstchild;        while (node) {            //...            node = node.nextsibling;
Delete DOM node

before deleting a DOM node, be sure to delete the event that is registered on that node , whether it is an event registered in observe or attachevent mode, which will result in memory that cannot be reclaimed. In addition, between RemoveChild and Innerhtml= ', try to choose the latter. Because the result of monitoring in the sieve (Memory leak monitoring tool) is that the DOM node cannot be effectively freed using the event proxy with RemoveChild

Any event that can be bubbled can be handled not only on the event target, but also on any ancestor node of the target, and using this knowledge can attach the event handler to the higher place to handle the event handling of multiple targets. For situations where the content is dynamically incremented and the child nodes need the same event handler, the event registration can be referred to the parent node, so that there is no need to register the event listener for each child node . In addition, the existing JS library uses the observe method to create event listeners, which isolate the circular reference between the DOM object and the event handler, so you should try to create the event listener reuse call result in this way, and save it to the local variable beforehand.

        Avoid the call cost of multiple values        var h1 = element1.clientheight + num1;        var h2 = element1.clientheight + num2;        Can be replaced by:        var eleheight = element1.clientheight;        var H1 = eleheight + num1;        var h2 = eleheight + num2;
Note NodeList

Minimizing the number of accesses to nodelist can greatly improve the performance of the script

        var images = document.getelementsbytagname (' img ');        for (var i = 0, len = images.length; i < Len; i++) {        }

When writing JavaScript, be sure to know when to return NodeList objects so that you can minimize access to them

  • A call to getElementsByTagName () was made
  • Gets the ChildNodes property of the element
  • Gets the attributes property of the element
  • Access to special collections such as document.forms, document.images, etc.
  • To understand that when using NodeList objects, reasonable use can greatly improve the code execution speed optimization cycle

    There are several ways to optimize loops

  • Impairment iterations
  • Most loops use an iterator that starts at 0 and increases to a specific value, and in many cases, the iterator that continues to decrement in the loop is more efficient, starting from the maximum value

  • Simplified termination conditions
  • Since the termination condition is calculated for each cycle, it is necessary to ensure that it is as fast as possible, that is, to avoid property lookups or other operations, preferably to save the loop control to a local variable, that is, when an array or list object is traversed, the length is saved to the local variable in advance. Avoid repeating values at each step of the loop.

            var list = document.getElementsByTagName (' P ');        for (var i = 0; i < list.length; i++) {            //...        }        To be replaced by:        var list = document.getElementsByTagName (' P ');        for (var i = 0, L = list.length; i < L; i++) {            //...        }
  • Simplifying the Loop body
  • The loop body is the most executed, so make sure it is optimized to the maximum extent possible

  • Test loop after use
  • In JavaScript, we can use the for (;;), while (), three loops in the three loops, in fact, because he needs to query the hash key, as long as it can, should be used sparingly. for (;;) And while loops, the while loop is more efficient than for (;;), possibly because for (;;) Structure of the problem, need to jump back often.

            var arr = [1, 2, 3, 4, 5, 6, 7];        var sum = 0;        for (var i = 0, L = arr.length; i < L; i++) {            sum + = Arr[i];        }        Can be considered to be replaced by:        var arr = [1, 2, 3, 4, 5, 6, 7];        var sum = 0, L = arr.length;        while (l--) {            sum + = Arr[l];        }

    The most common for loop and while loop are pre-test loops, which, like Do-while, can avoid the calculation of the initial termination condition and therefore run faster. Expand Loops

    When the number of loops is determined, eliminating loops and using multiple function calls tends to be faster. Avoid double interpretation

    If you want to improve your code performance, avoid strings that need to be interpreted in JavaScript, that is,

  • use as little as possible Eval function
  • Using Eval is equivalent to invoking the interpretation engine again at run time to run the content, which can take a lot of time, and the security issues with Eval are not to be overlooked.

  • Do not use Function Constructors
  • Do not pass string arguments to SetTimeout or setinterval

            var num = 0;        SetTimeout (' num++ ', ten);        Can be replaced by:        var num = 0;        function Addnum () {            num++;        }        SetTimeout (Addnum, 10);
    Shorten negative detection
           if (otest! = ' #ff0000 ') {            //do something        }        if (otest! = null) {            //do something        }        if (Otest!) = False) {            //do something        }        //Although these are correct, the same effect is done with logical non-operators:        if (!otest) {            //do something        }
    Conditional Branch
  • Arrange conditional branching from high to low in order of probability: reduces the number of times the interpreter can detect a condition
  • When multiple (>2) conditional branches of the same condition are used, using switch over the If:switch branch is more efficient than if, which is especially noticeable under IE. 4 branch of the test, ie under switch execution time is about half the IF.
  • Using the three-mesh operator to override conditional branching
  •         if (a > B) {            num = A;        } else {            num = b;        }        Can be replaced by:        num = a > b? a:b;
    Using constants
  • Duplicate values : Any value that is used in multiple places should be extracted as a constant
  • user Interface String : Any string to be displayed to the user should be extracted to facilitate internationalization
  • URLs: Resource locations are easily changed in Web applications, so it is recommended to store all URLs in a common place
  • any value that may change: whenever you use a literal value, you have to ask yourself whether the value will change in the future, and if the answer is "yes", then the value should be extracted as a constant.
  • Avoid comparisons with null

    Because JavaScript is a weak type, it does not do any automatic type checking, so if you see code that compares null, try using the following technique to replace

  • If the value should be a reference type, use the instanceof operator to check its constructor
  • If the value should be a base type, the action typeof checks its type
  • If you want the object to contain a particular method name, use the typeof operator to ensure that the method of the specified name exists on the object
  • Avoid global volume

    Global variables should be capitalized in all letters, and the words should be underlined to connect them . Avoid global variables and functions as much as possible, minimizing the use of global variables, because all JavaScript contained in one page runs in the same domain. So if you declare a global variable or a global function in your code, the same name variables and functions in the script file loaded in the following code will overwrite (overwrite) your.

    Bad global variables and global functions var current = Null;function init () {//...} function Change () {    //...} function Verify () {    //...} There are a lot of solutions, Christian Heilmann The recommended method is://If the variables and functions do not need to be referenced in the "outside", then they can all be wrapped up using a method without a name. (function () {var current = Null;function init () {    //...} function Change () {    //...} function Verify () {    //...}}) ();//If variables and functions need to be referenced "outside", you need to put your variables and functions in a "namespace"//we use a function as a namespace instead of a Var, because declaring the function in the former is simpler, and can protect privacy data MyNamespace = function () {    var current = null;    function init () {        //...    }    function Change () {        //...    }    function Verify () {        //...    } All functions and properties that need to be called outside the namespace are written in return with    return {        init:init,        //You can even name an alias for functions and properties        set:change    };
    Respecting the ownership of objects

    Because JavaScript can modify any object at any time, it can overwrite the default behavior in an unpredictable way, so if you are not responsible for maintaining an object, its object, or its methods, then you should not modify it, specifically:

  • Do not add attributes to an instance or prototype
  • Do not add methods to instances or prototypes
  • Do not redefine methods that already exist
  • Do not repeatedly define the methods that other team members have implemented, never modify the objects that are not owned by you, and you can create new features for objects in the following ways:
  • Create a new object that contains the functionality you want and use it to interact with related objects
  • Create a custom type, inherit the type that you want to modify, and then add additional functionality for the custom type
  • Circular references

    If a circular reference contains a DOM object or an ActiveX object, a memory leak occurs. The consequence of a memory leak is that the memory is not released by the browser until the browser is closed, even if the page is refreshed.

    A simple circular reference:

            var el = document.getElementById (' myelement ');        var func = function () {            //...        }        El.func = func;        Func.element = El;

    However, this is not usually the case. Typically, circular references occur when you add closures as Expendo for DOM elements.

            function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }        }        Init ();

    When Init executes, the current context is called the contextual. At this time, the context refers to the context referenced by the El,el reference function,function. A circular reference is formed at this time.

    Here are 2 ways to resolve circular references:1) empty DOM object

           function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }        }        Init ();        Can be replaced by:        function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }            el = null;        }        Init ();

    The El is empty, and the context does not contain a reference to the DOM object, which interrupts the loop application.

    If we need to return the DOM object, we can use the following method:

            function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }            Return el;        }        Init ();        Can be replaced by:        function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }            try {                return el;            } finally {                el = null;            }        }        Init ();

    2) construct a new context

            function init () {            var el = document.getElementById (' myelement ');            El.onclick = function () {                //...            }        }        Init ();        Can be replaced by:        function Elclickhandler () {            //...        }        function init () {            var el = document.getElementById (' myelement ');            El.onclick = Elclickhandler;        }        Init ();

    The function is pumped into a new context so that the context of the function does not contain a reference to the El, thus interrupting the circular reference. Dom objects created from JavaScript must be append to the page

    ie, script created by the DOM object, if not append to the page, refresh the page, this part of the memory is not recycled!

            function Create () {            var gc = document.getElementById (' gc ');            for (var i = 0; i < i++) {                var el = document.createelement (' div ');                el.innerhtml = "Test";                The following sentence can be commented out, to see the browser in the Task Manager, click on the button and then refresh the memory changes                gc.appendchild (EL);}        }
    Frees memory occupied by DOM elements

    Setting the innerHTML of the DOM element to an empty string frees up the memory occupied by its child elements.

    In rich apps, users might spend a long time on a page, and use this method to free up memory used by more and more DOM elements. Releasing JavaScript objects

    In rich applications, as the number of instantiated objects increases, memory consumption becomes larger. Therefore, you should release references to objects in a timely manner so that the GC can reclaim those memory controls.

    object: obj = null

    Object properties: Delete Obj.myproperty

    Array item: Use the Splice method of the array to release the unused item in the array to avoid string implicit boxing

    A method call to string, such as ' xxx '. Length, the browser makes an implicit boxing operation that converts the string into a string object first. It is recommended that you use the following syntax when declaring a string that may be using a string instance method:

    var myString = new String (' Hello world '); loosely coupled

    1. Decoupling Html/javascript

    Tight coupling between JavaScript and HTML: JavaScript written directly in HTML, using <script> elements that contain inline code, assigning event handlers using HTML attributes, and more

    Tight coupling between HTML and javascript: JavaScript contains HTML and then uses innerHTML to insert a piece of HTML text into the page

    It's supposed to be a separation of layers, so it's easy to identify the source of the error, so we should make sure that HTML rendering should be kept separate from JavaScript as much as possible.

    2. Decoupling Css/javascript

    The only source of the problem should be CSS, and the only source of behavioral problems should be JavaScript, which is loosely coupled between layers to make your application easier to maintain, so code like the following element.style.color= "Red" Try to change to element.classname= "edit", and do not embed JavaScript in the CSS with an expression

    3. Decoupling application/Event handlers

    Detach the application logic from the event handler: an event handler should be extracted from the event object and passed to a method that handles the application logic. The benefits of doing this first make it easier for you to change the events that trigger a particular process, and second you can test your code without attaching events, making it easier to create unit test performance considerations

    1, try to use the native method

    2. Switch statement is faster than if

    By organizing case statements in the most likely to the most improbable order

    3, bit operation faster

    A bitwise operation is faster than any boolean or arithmetic operation when a numeric operation is performed.

    4, skillfully use | | and the && Boolean operator

            function EventHandler (e) {            if (!e) e = window.event;        }        Can be replaced by:        function EventHandler (e) {            e = e | | window.event;        }
            if (myobj) {            dosomething (myobj);        }        Can be replaced by:        myobj && dosomething (myobj);
    Avoid mistakes should be noted in the place

    1. Add a semicolon at the end of each statement

    In an if statement, even if only one statement of the conditional expression is to be enclosed in {}, in case of a logical error following the addition of the statement

    2, use the + number should be cautious

    JavaScript differs from other programming languages in that, in JavaScript, ' + ' can be used as a unary operator to convert a string to a number, in addition to a numeric value added together with a string. Therefore, if used improperly, it may be confused with the self-increment ' + + ' to cause a calculation error

            var Valuea =;        var valueb = "Ten";        Alert (Valuea + valueb);     ouput:2010         Alert (Valuea + (+VALUEB));  output:30         Alert (Valuea + +valueb);    output:30         Alert (Valuea + + valueb);     Compile Error

    3. Use return statement to pay attention to

    A return statement that returns a value does not enclose the return value with () parentheses, and if the expression is returned, the expression should be on the same line as the return keyword to avoid compression, and the compression tool automatically adds semicolons to the results that are inconsistent with the developer

            function F1 () {            var Valuea = 1;            var valueb = 2;            return Valuea + valueb;        }        function F2 () {            var Valuea = 1;            var valueb = 2;            return            Valuea + valueb;        }        Alert (F1 ());  Output:3         alert (F2 ());  ouput:undefined
    The difference between = = and = = =

    Avoid assigning values in the conditions section of the IF and while statements, such as if (a = b), should be written as if (a = = B), but it is preferable to use the congruent run if the comparison is equal, that is, using the = = and!== operators will be better relative to = = and! =. The = = and! = operators Convert type casts

            var Valuea = "1";        var valueb = 1;        if (Valuea = = Valueb) {            alert ("Equal");        }        else {            alert ("Not Equal");        }        Output: "Equal"        if (Valuea = = = Valueb) {            alert ("Equal");        }        else {            alert ("Not Equal");        }        Output: "Not Equal"
    Do not use the raw-bias syntax

    Do not use the raw-biased syntax, write confusing code, although the computer can correctly identify and run, but the obscure code is not convenient later maintenance function return to the unified type

    Although JavaScript is a weak type, for functions, the previous return of the integer data, followed by the return of the Boolean value can be compiled and run through the normal, but for specification and later maintenance is easy to understand, should ensure that the function should return a uniform data type always check the data type

    To check all data entered by your method is for security, and on the other hand, for usability. Users enter the wrong data whenever and wherever they are. This is not because they are stupid, but because they are busy and think differently from you. Use the TypeOf method to detect if the input your function accepts is valid when using single quotes and when to use double quotes

    Although in JavaScript, double and single quotation marks can represent strings, in order to avoid confusion, we recommend using double quotation marks in HTML, single quotes in JavaScript, but in order to be compatible with each browser, but also to parse without error, when defining a JSON object, It is best to deploy with double quotes

  • Run the JavaScript validator with JSLint to make sure there are no syntax errors or that the code does not have the potential to ask
  • Compression tools are recommended to compress JS files before deployment
  • UTF-8 for Unified file encoding
  • The JavaScript program should be placed in the. js file as much as possible in the form of <script src= "Filename.js" > in HTML when it needs to be called. If the JavaScript code is not specific to the HTML file, you should try to avoid writing JavaScript code directly in the HTML file. Because this will greatly increase the size of the HTML file, not conducive to the compression of code and the use of caching. In addition, <script src= "filename.js" > tags should be placed in the back of the file as far as possible, preferably placed in front of </body> tags. This reduces the load time of other components in the page because of the loading of JavaScript code.
  • Never ignore the code optimization work, refactoring is a project from the beginning to the end of the need for continuous work, only the continuous optimization of code to make code execution more efficient and better

    Excerpt: JavaScript performance Optimization Trivia Summary

    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.