JS Learning Note 12_ optimization

Source: Internet
Author: User

I. maintainability optimization 1. Add comments

Annotations can enhance the readability and maintainability of the code, and of course, the ideal is full of annotations, but this is not realistic. So we just need to add a note to some key places:

    • Functions and methods: Especially the return value, because it is not directly visible

    • Large segment Code (function Module): Description module function

    • Complex algorithms: Write key points for easy understanding

    • Hack: Explain to fix what problem, current plan is perfect, can improve

2. "Implied" variable type

Implied by an initial value, for example:

var found = False;var Count = 1;var name = "; var student = null;
3. Decoupling (layering)
    • Structure Layer: HTML

    • Behavior Layer: JS

    • Presentation layer: CSS

Try not to "ultra vires", if you really want to exceed the authority, you should also use the document or note description. Try not to have tight couplings, such as:

    • Js-html:

      elem.innerhtml = ' <div class= ' block >
    • JS-CSS:

      Elem.style.color = ' #e0e0e0 ';//preferably in the following way (set the class, do not set the style directly)//elem.classname = ' My_class ';
    • JS-JS:

      Logical coupling Elem.onclick = function (e) {  if (txt.value!== null && txt.value!== "&& ...) {    //dom operation  }}//better replace (detach logical function block) function IsValid () {  return txt.value!== null && txt.value!== ' && function display () {  //dom operation}elem.onclick = function (e) {  if (IsValid ()) {    display ()}  }

      Several principles to avoid logical coupling:

      • Do not pass the event object, only the required data

      • Triggering an event should not be the only way to perform an action

      • Event handlers should handle only event-related data (get event sources, coordinate values, and so on), and then transfer the processing to the application logic

4. Coding Principles
    • Respect object ownership, do not casually modify other people's objects, specific requirements:

      • Do not add attributes or methods to instances/prototypes

      • Do not override an existing method

      Optional options:

      • Composition: Create a new object that implements the required functionality, referencing the desired object

      • Inheritance: Create a custom type, inherit the type that needs to be modified, and then add additional features

    • Use namespaces to avoid global variables, such as:

      var Mysystem = {};mysystem.mod1 = {...};
    • Use constants to improve maintainability, such as:

      var consts = {}; Consts.img_path = '. /imgs/';

      Note: Constants include commonly used CSS class names and any other values that might affect maintenance

Two. Performance optimization 1. Avoid long scope chain lookups

Save global variables that require multiple references as local variables

2. Try not to use the WITH statement

The With statement extends the scope, there is the overhead of long scope lookups, and can be replaced with a saved local variable (no with convenience, but much better)

3. Avoid unnecessary property lookups
  1. Try to save the reused value as a local variable, for example:

    Do not use the following code (6-time attribute lookup) var qs = window.location.href.substring (window.location.href.indexOf ('? ')); /should use the following code (4 times, and more readable) var url = window.location.href;var qs = url.substring (Url.indexof ('? '));
  2. Optimize loops

    • Reduced iteration faster (I –)

    • Simplified termination conditions, each cycle will check the termination conditions, simplifying conditions can improve efficiency

    • Simplifies the loop body, minimizing the amount of computation inside the loop body

    • After using the test loop (do...while), you can avoid the judgement before the first cycle.

  3. Expand Loops

    If the number of cycles is determined, it is best not to use loops because the loop has additional overhead for creating loops and processing termination conditions, such as:

    for (i = 0;i < 2;i++) {  process (arr[i]);} The following faster process than above (arr[0]);p rocess (arr[1]);p rocess (arr[2]);

    If the number of cycles is not determined, you can use Duff technology (invented by Tom Duff) to expand a part of the cycle to improve efficiency, such as:

    Credit:jeff Greenberg for JS implementation of Duff ' s device//assumes values.length > 0var iterations = Math.ceil (values. LENGTH/8) var startAt = values.length% 8;var i = 0;do {    switch (startAt) {case        0:process (values[i++]);        Case 7:process (values[i++]);        Case 6:process (values[i++]);        Case 5:process (values[i++]);        Case 4:process (values[i++]);        Case 3:process (values[i++]);        Case 2:process (values[i++]);        Case 1:process (values[i++]);    }    startAt = 0;} while (--iterations > 0);//above code from: http://www.cnblogs.com/kylindai/archive/2013/12/04/3458476.html

    or another faster way to Duff:

    Credit:speed up Your Site (New Riders, 2003) var iterations = Math.floor (VALUES.LENGTH/8); var leftover = Values.length % 8;var i = 0;if (Leftover > 0) {do    {        process (values[i++]),    } while (--leftover > 0);} Do {    process (values[i++]);    Process (values[i++]);    Process (values[i++]);    Process (values[i++]);    Process (values[i++]);    Process (values[i++]);    Process (values[i++]);    Process (values[i++]);} while (--iterations > 0);//above code from: http://www.cnblogs.com/kylindai/archive/2013/12/04/3458476.html
  4. Avoid double interpretation

    Double interpretation means: Use JS to parse JS. Specifically, use the eval () function or the new function (Strcode) or settimeout (Strcode)

    The disadvantage of double interpretation: the need to start a parser to parse, there is a lot of overhead, much slower than the direct parsing

  5. Native method Faster

    Native methods are compiled with C/s + + modules, so much faster

  6. Switch is faster than If-else

    The reason is not good to say, can refer to Csdn

  7. Bit arithmetic is not faster

    In other languages to simplify the math operations can improve the calculation speed, but JS does not say that, because JS internal only a numeric type (double), so do bit operations need to toss: double–int– do bit operation –double, performance imaginable

  8. Reduce the number of statements

    • Declaration of multiple variables with 1 var

    • Insert iteration value, arr[i++] A statement is done, do not have to separate i++ into a statement

    • With array/object literals, the number of lines of code becomes significantly less.

  9. Dom optimization

    • Reduce on-site updates and can be optimized with documentfragment

    • It is faster to create a DOM node with innerHTML than to create a bunch of nodes, but there are js-html coupling problems , carefully consider

    • Delegate with Event

    • Note Collections of live updates (NodeList, NamedNodeMap, htmlcollection)

      In addition to saving references as local variables, it is also important to note that accessing their properties also requires re-querying, such as: var IMGs = document.images; Access Imgs.length also needs to be checked again

Three. Release optimization
    1. Check your code with a validation tool (such as jslint) and discover potential problems beyond syntax errors

    2. Remove annotations (for security reasons)

    3. Combine JS files to minimize the number of external files

    4. Compressed code (such as Yui compressor), reduce the size of the code itself, can also confuse the code, improve security, but confusing the code itself is risky, may cause errors

    5. Turn on server compression, such as the Gzip module

JS Learning Note 12_ 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.