Javacript Optimization 2

Source: Internet
Author: User

The previous article outlines some of the tips used in JavaScript, and this article goes on to describe memory management, loose coupling, performance tips, points to avoid errors

Memory management

1. Circular reference

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.

2. Dom objects created by 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);}    }

3. Releasing 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.

4. Release 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 array's splice method to dispose of unused item in the array

5. 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 then you can test the code without attaching the event, making it easier to create unit tests

Performance considerations

1, try to use the native method

2. Switch statement is faster than if

Organize case statements in the most unlikely order possible

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 = 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 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

4, = = and the difference between = = =

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"

5, do not use the raw-biased grammar

Do not use the raw-biased syntax, write confusing code, although the computer can correctly identify and run, but the obscure code is inconvenient to maintain later

6. function return Unified type

Although JavaScript is a weak type, for functions, the previous return of the integer data, the return of the Boolean value in the compilation and operation can pass normally, but for specification and later maintenance is easy to understand, should ensure that the function should return a uniform data type

7. Always check 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 your function accepts input as legitimate

8. When to use single quotation marks and when to use double quotation marks

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's best to use double quotes

9. Deployment

    • 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.

Categories: Scripting and functional programming

Javacript Optimization 2

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.