JS Performance optimization

Source: Internet
Author: User
Tags case statement event listener

Http://www.admin10000.com/document/6005.html Preface has been learning javascript, but also have seen the "sharp development of jquery core details and practice," the Book's evaluation only two words sharp,  Maybe it's not enough to understand JavaScript or that you're too stupid, and that you're not so good at thinking too much about it that some of the essence is not too deep to understand.  In view of want to let oneself have a promotion, cannot enter a broader world, must find a own residence to survive, so usually consciously or unconsciously to accumulate some common knowledge using jquery, especially for performance requirements This piece, will always think is not a better way to Achieve. Here are some tips I've summed up, for reference only. (i'll start with a headline and then use a short paragraph to illustrate the meaning and then use a demo to make it easy to say) avoid global lookups in a function that uses global objects as local variables to reduce global lookups, because accessing local variables is faster than accessing global variables.        Search () {//when I want to use the current page address and host Domain name alert (window.location.href + window.location.host);            }//the best way is to save the function search () {var location = Window.location with a simple variable first;        Alert (location.href + location.host);        If the timer is for running code, you should not use settimeout instead of 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, 10); }} 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 than + =, such as s+=a;  s+=b;  s+=c;      It should be written as 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 with the Join method var buf = [];       for (var i = 0; i < i++) {buf.push (i.tostring ());  } var all = Buf.join (""); Avoid similar with statements and functions, the WITH statement creates its own scope, and therefore 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. Try not to use the WITH statement when you can not use 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; It is generally best to convert a number to a string ("" + 1), although it looks uglier, but in fact the efficiency is the highest, performance says: ("" +) > String () >. toString () > new String () How to convert a string into a number? The simplest method is multiplied by 1; alert (typeof ("500") * *//number floating-point numbers converted to integers many people like to use parseint (), in fact parseint () is used to convert a string into a number, rather than a floating-point and integer conversion between, we should use Math.floor () or Math.Round () Various types convert var str = "3.6415926"; var to_string = "" + str; Alert ("to_string:" + str); 3.1415926var To_int = ~~str; Alert ("to_int:" + TO_INT)//3 similar to math.floor ("3.6")//3var to_float = 1* str; Alert ("to_float:" + To_float)//3.1415926var To_boolean =!! Str Alert ("to_boolean:" + to_boolean)//true (string lengths greater than 0 digits are not equal to 0 true!) ) var To_arr = [str]; Alert ("to_arr;" +to_arr)//[3.1415926] var myVar = "3.14159", str = "" + myVar,//to String i_int = ~ ~ MyVar,//to the 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 to 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. multiple type declarations in JavaScript all variables can be declared with a single Var statement, which is the combination of statements to reduce the execution time of the entire script, as in the above code, on theThe format of the surface code is also very normative, let a person see on the clear. Insert an iterator such as Var name=values[i]; i++; the preceding two statements can be written as Var name=values[i++] using the direct amount 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 Object ();        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 before you add it to the existing Document.            for (var i = 0; i < i++) {var ele = document.createelement (' p ');            ele.innerhtml = i;        Document.body.appendChild (ele);        }//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 the One-time Innerhtml assignment instead of building DOM elements for large Dom changes, using innerHTML is much faster than creating 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);        Use FirstChild and nextsibling instead of childNodes to traverse the DOM element 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; Before deleting a DOM node, be sure to delete the event that is registered on that node, whether it is an event that is 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 RemoveChild event proxy any events that can be bubbled can be handled not only on the event target, but also on the targetCan be processed on any ancestor node, using this knowledge to attach event handlers to higher-level event handling for multiple targets, as well as the case where the content is dynamically increasing and the child nodes need the same event handler, the event can be registered to the parent Node. This makes it unnecessary to register event listeners for each child Node.        In addition, the existing JS Library uses observe mode to create the event listener, the implementation of which separates the DOM object and the event handler function circular reference, so should try to use this way to create the event to listen to the repeated use of the result of the call, save to the local variable//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 • Make a pair of get  Call of Elementsbytagname () • Gets the ChildNodes property of the element • Gets the attributes attribute of the element • Access to special collections such as document.forms, document.images, etc. To understand that when using the nodelist object, reasonable use will greatly improve the code execution speed optimization cycle can be used in the following ways to optimize the loop/decrement iteration most loops use an iterator that starts at 0, increases to a specific value, and in many cases starts with the maximum value, An iterator that continuously reduces value in a loop is more efficient and simplifies the termination condition because the termination condition is computed for each cycle, it is necessary to keep it as fast as possible, that is, to avoid property lookups or other operations, preferably by saving the loop control to a local variable, that is, when an array or List object is traversed,Save length in advance to local variables to 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++) {//...} • To simplify the loop body loop body is the most executed, so to ensure that it is optimized optimally • After using the test loop in javascript, we can use the for (;;), while (), for (in) three loops, in fact, in these three loops the efficiency of the for (in) is very poor, Because he needs to query the hash key, as long as you can, you should try to use Less. 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 for substitution with: 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 the Eval function as little as Possible. using eval is equivalent to calling the solution again at run timeThe release engine runs on content, It takes a lot of time, and the security issues with Eval are not negligible.        • Do not use the function constructor do not pass string arguments to settimeout or setinterval var num = 0;        SetTimeout (' num++ ', 10);        can be replaced by: var num = 0;        function Addnum () {num++;  } setTimeout (addnum, 10); Shortened negative detection if (otest! = ' #ff0000 ') {//do something} If (otest! = Null) {//do Some        thing} if (otest! = False) {//do Something}//although These are correct, the same effect is done with logical non-operators: If (!otest) {//do something} conditional branching • Conditionally branching, from high to low in order of probability: reduces the number of times the interpreter can detect a condition • When a multiple (>2) conditional branch of the same condition is used, switch is better than If:switch Branch selection is more efficient than if, especially in Ie. 4 branch of the test, ie under switch execution time is about half the If.        • Use 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; Use constants • Duplicate Values: Any value used in multiple locations should be extracted as a constant • user interface string: Any string to be displayed to the user should be extracted to facilitate internationalization urls: in a Web application, the resource location is easily changed, so it is recommended to store all the URL 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 ifThe answer is "yes", then this value should be extracted as a constant. Avoid comparisons with null because JavaScript is weakly typed, It does not do any automatic type checking, so if you see code that compares with null, try the following technique substitution • If the value should be a reference type, check its constructor using the instanceof operator · If the value should be a basic type, the effect typeof check its type • If you want the object to contain a specific method name, use the typeof operator to ensure that the method that specifies the name exists on the object to avoid global global variables should all be capitalized, and the words are concatenated with an _ Underscore. 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.        Init:init,//you can even name an alias for functions and properties set:change}; Respecting the ownership of objects because JavaScript can modify arbitrary objects 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 an attribute to an instance or prototype • Do not add methods to instances or prototypes • Do not redefine methods that already exist • Do not repeat 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 by: • Create new objects that contain the required Functionality. and use it to interact with related objects • Create custom types, inherit types that need to be modified, and then add additional feature circular references for custom types 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.        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) constructs 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 object created by javascript, must be append to the page under ie, script to create 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 the button and then refresh the memory changes Gc.appendchild (el);  Releasing the memory occupied by the DOM element sets the innerHTML of the DOM element to an empty string, freeing 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, memory consumption is increasing as the number of instantiated objects Increases.  therefore, you should release references to objects in a timely manner so that the GC can reclaim those memory Controls. Object: obj = null object property: Delete obj.myproperty array item: Use the Array's splice method to release the unused item in the array to avoid string implicit boxing of the method call to string, such as ' xxx '. length, The browser will perform an implicit boxing operation, Converts a string to a string object First.  It is recommended to use the following notation when declaring a string with the possibility of using string instance methods: var myString = new string (' Hello world ');  Loosely coupled 1, decoupling html/javascript JavaScript and HTML tightly coupled: JavaScript written directly in html, using <script> elements containing inline code, assigning event handlers using HTML attributes, etc. The tight coupling between HTML and javascript: JavaScript contains html, and then using innerHTML to insert a piece of HTML text into the page should actually be a hierarchy of separation, so it is easy to determine the source of the error, So we should make sure that HTML rendering should be separated from JavaScript as much as possible 2. The only source of decoupling css/javascript display problems should be css, the only source of behavioral problems should be javascript, The layers remain loosely coupled to make your application easier to maintain, so code like the following element.style.color= "red" as much as possible to element.classname= "edit", and do not use expressions in CSS Embedded JavaScript 3, decoupled 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 the code without attaching an event, making it easier to create unit test performance Considerations 1, try to use native method 2, switch statement faster relative if The bitwise operation is faster than any boolean or arithmetic operation by organizing the case statement in the most likely to the most improbable order 3, The bitwise operation is more than'm going aunt for the numeric operation 4, skillfully using | |        and && 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 errors should be noted in place 1, each statement at the end of a semicolon in the if statement, even if the conditional expression is only one statement to be enclosed with {}, in order to avoid subsequent if you add a statement after the logic error 2, using the + number should be cautious JavaScript and other programming languages are different, in the In JavaScript, ' + ' can be used as a unary operator to convert a string to a number, except for the addition of a numeric value and a string Connection.        thus, if used improperly, it may be confused with the self-increment ' + + ' resulting in a calculation error var Valuea = 20;        var Valueb = "10";     Alert (valuea + valueb);  ouput:2010 Alert (valuea + (+valueb));    OUTPUT:30 Alert (valuea + +valueb);     OUTPUT:30 Alert (valuea + + valueb); Compile error 3, Use the return statement to note that a return statement with a returned value does not use () parentheses to enclose the return value, and if an expression is returned, the expression should be on the same line as the return keyword to avoid compression.            The compression tool automatically adds a semicolon to return the result 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 ()); The difference between ouput:undefined = = and = = = avoids assigning values in the conditional portion 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 runner if the comparison is equal, that is, the = = = and!== Operators will be better relative to = = and! =.        the = = and! = operators perform type casts of 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, write confusing code, although the computer can correctly identify and run, but the obscure code is not convenient to maintain the function back to the unified type although JavaScript is weakly typed, the In terms of functions, the previous return of the integer data, followed by the return of the Boolean value in the compilation and operation can pass normally, but in order to standardize 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 your method input all data, on the one hand for security, On the other hand is also 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 legitimate when using single quotes, when using double quotes while in javascript, double and single quotes can represent strings, in order to avoid confusion, we recommend using double quotes in html, Use single quotes in javascript, but in order to be compatible with individual browsers and to parse without errors, it is best to use double quotation marks when defining JSON objects • Run JavaScript with JSLintValidator to ensure that there is no syntax error or that the code is not potential to ask • Pre-deployment using the compression tool to compress JS files • File encoding Unified with the Utf-8 JavaScript program should be placed in The. JS file, need to call in the HTML to <script SRC = "filename.js" > is included in the Form. 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 code optimization, refactoring is a continuous effort from the start of the project to the end, and only constant optimization of code can make the code more Efficient.

JS Performance optimization

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.