Js function reference, memory overhead _ javascript tips-js tutorial

Source: Internet
Author: User
Function reference. For memory overhead analysis, you can refer to the following code:

The Code is as follows:


Var arr = [];
Var cc = function () {alert ('xx ');};


For (var I = 0; I <2; I ++ ){

Arr [I] = function () {alert ('yy ');}
Arr [I + 10] = cc;
}

Console. group ('start ')
Console. group ('1 ')
Console.info (arr [0] = arr [1]);
Console.info (arr [0] === arr [1]);

Console.info (arr [0]. toString ());
Console.info (arr [1]. toString ());
Console. groupEnd ('1 ')


Console. group ('2 ')
Console.info (arr [10] = arr [11]);
Console.info (arr [10] === arr [11]);

Console.info (arr [10]. toString ());
Console.info (arr [11]. toString ());
Console. group ()
Console. groupEnd ('start ');



The running result in Firefox firebug console is as follows:




Analysis:

The loop of the fifth line of code starts. After the loop ends, the arr array returns the following result:
Arr [0] = function () {alert ('yy ');}
Arr [1] = function () {alert ('yy ');}
Arr [10] = cc
Arr [11] = cc
You can see the result in the console ,.
Arr [0] is not equal to arr [1]
However, arr [10] is equal to arr [11] Because it references the previously defined variable.
Actually, in the loop process, the function () {alert ('yy');} is redefined ');}
The toString output content of arr [0] and arr [1] is the same. However, the two are independent methods that occupy their respective memory. Therefore, to save memory, functions can be defined outside the loop.
The precondition for a function to be defined outside the loop is that the function does not accept variables that change within the loop.
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.