variables, scopes, and memory issues in JavaScript

Source: Internet
Author: User
Tags disk defragmenter

1. Variables

The type of the value of the variable: base type value and reference type value of two.

Base type:Undefined,Null,Boolean,String, Number , the values of these five basic data types occupy a fixed amount of space in memory, so they are stored in stack memory (storing simple data).

Reference type value: Refers to the object stored in the heap memory, the size is not fixed, the variable is only a pointer to the object (a storage location in memory, where the specific object is stored), the pointer is the memory address is fixed, so the pointer location can be stored in the stack memory, However, specific objects are stored in heap memory.

The base type value is access by value, and the reference type value is access by reference.

2. Copy variable values

There are differences between copy base type values and reference type values.

Base Type value: Copies the base type value from one variable to another, copying the value to the location of the new variable. Therefore, two variables are unrelated, and one of the operations does not affect the other.

Var num=10;

Var Num2=num;

Reference type value: Modifying one of them affects the other, and both points to the same object.

Var obj1=new Object ();

Var obj2=obj1;

Stack memory

3. Passing Parameters

the parameters of all functions in ECMAScript are passed by value, that is, the values outside the function are copied to the parameters within the function. The value of the base type and the reference type are passed in the same way as the base type and the reference type variable (as above). Variable access is accessed by value and by reference, while parameter passing can only be passed by value.

such as function SetName (obj) {

Obj.name= ' Hello ';

Obj=new Object ();

Obj.name= ' World ';

}

Var c=new Object ();

SetName (c);

Alert (C.name); Hello

If it is passed by reference, when obj points back to an object, C also points to the new obj, then C the name attribute should be World.

4. Garbage collection

Javascript uses a tag - purge policy

Three of the most basic garbage collection algorithms,

Reference count (Reference Counting) Algorithm: This may be the earliest thought of the method. The image Point says that the reference count can be understood so that the house has a lot of white paper, which is like memory. Using memory is like writing on these papers. Memory can be used casually, but there is a condition that anyone using a piece of paper must write a count on the corner of the paper1, if2when a person uses a piece of paper at the same time, the count becomes2, and so on. When a person finishes using a piece of paper, the count on the corner must be reduced1, so that once the count becomes0, it satisfies the garbage collection condition, and the robot will throw the paper into the bin immediately. A garbage collector based on a reference counter runs faster and does not interrupt program execution for long periods of time, and it is appropriate to run programs in real time. But the reference counter increases the cost of executing the program, and there is one big problem with this algorithm, which is that once a circular reference is generated, the memory is compromised. As an example, weNewthe2an Objectaand theb, at this time,aand thebThe Count is1, and then, we putaa property that points tob,ba property that points toa, at this point, because of the referenced relationship,aand thebThe count has become2, when the program runs at the end, exit the scope, the program automaticallyathe Count minus1, since the lastaThe count is still1, and therefore,awill not be released, likewise,bThe final count is also1,bWill not be released, the memory is so leaked!

Mark-Clear (Mark-sweep) Algorithm: The same example of room and white paper, this time the rules have been revised. White paper is still used casually, and, in the beginning, do not need to do what marks, but at some point, the robot will suddenly command everyone to stop, at this time, need everyone in their own still need to make a mark on the white paper, after everyone has done the mark, the robot will put all those unmarked white paper into the dustbin. As its name implies, the execution of the tag-purge algorithm is divided into two phases: Mark and purge. The idea of the step execution lays the foundation of the modern garbage collection algorithm. Unlike the reference counting algorithm, the tag-purge algorithm does not require a running environment to monitor every memory allocation and pointer operation, and as long as the point of each pointer variable is tracked in the "mark" phase-a garbage collector implemented in a similar way is often referred to as a tracking collector (Tracing Collector). Of course, Mark-clearly the defect of the algorithm is also obvious, first of all, the efficiency problem, in order to mark, must suspend the program, long wait, second, the tag cleanup algorithm will cause memory fragmentation, such as is marked to clear only a few small blocks of memory, and we are going to apply for some of the large amount of memory, then the memory just cleared out , it still can't be used. Solutions, common with2, one is clear and then the memory is copied, like a Disk Defragmenter, all the memory that is still in use, move the freed memory together。

The second option is not to move the memory, but by the size of the classification, set up a series of linked lists, the fragments are connected and managed by size, (4 bytes of memory a linked list,8 bytes of memory a linked list ...) If we need 4 bytes of memory, we'll fetch it from the 4 -byte list, which requires A byte, from 16 bytes of the linked list to fetch, only to a certain time, such as the program idle or large chunks of memory space, will be organized to merge these fragments.

This algorithm is used by IE for the garbage collection of JavaScript .

Replication (copying) algorithm : Themark-sweep algorithm is inefficient, and as a result, a new kind of strange idea, we will change the rules: or room and white example, this time we divide the room into the left and right 2 part, at the beginning, everyone is on the left, white paper is still used casually, a certain time, the robot will call everyone to stop, this time do not mark, you just take the white paper you need to transfer to the right to go (equivalent to the existing program copy, The unused parts will naturally not be copied), the useless paper will be left, and then the robot would clean up all the garbage on the left (equivalent to the half of the memory used to empty), the next time the garbage collection is done in the same way, but this time from the right to the left to migrate. The efficiency of this algorithm is very high, unfortunately, the memory consumption is too large, especially in 1960 years, memory can be more than hypocrite, directly cut off half of the memory, obviously unacceptable.

Learn about the garbage collection algorithm, and then look at why the Internet has a memory leak.

InIE 6, forJavaScript ObjectInterior,JavaScriptusing AMark-and-sweepThe algorithm, which is mentioned earlier, is therefore purelyJavaScriptthe use of the object does not cause a memory leak, but forJavaScript Objectand externalObject (includeNative Objectand theVBScript Objectwait)the reference,IE 6use a reference count, so that memory leaks are generated. This is mentioned in the eighth chapter of the Rhino Book function section.

The following are some common scenarios for JavaScript memory leaks:

First, circular reference:

< script language = "JScript" >

var myglobalobject;

function Setupleak ()// generates a circular reference, thus causing a memory leak

{

First set up the script scope to element reference

Myglobalobject = document.getElementById ("Leakeddiv");

Next set up the element to script scope reference

document.getElementById ("Leakeddiv"). Expandoproperty = Myglobalobject;

}

<body onload = "setupleak ()" >

<div id = "Leakeddiv" ></div>

</body>

As we can see,myglobalobject points to a Dom object, and A property of the DOM object points to the Myglobalobject, circular references appear, memory leaks, the principle is as follows:

The solution is simple, after making sure that the attribute is no longer being used, add the following code:

function Breakleak () {// unlock Circular reference to resolve memory leak issues

document.getElementById ("Leakeddiv"). Expandoproperty = null;

}

It's easy to say, but it's not so easy to find and modify when our program is very complex.

variables, scopes, and memory issues in JavaScript

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.