search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript memory release problem_javascript skills

This article explains in detail the timing and methods of memory management and release by JavaScript and IE browsers. I hope it will be helpful to front-end developers.

An example of memory release

Copy code The code is as follows:


CollectGarbage is a unique attribute of IE, used to release memory. The method of use should be to set the variable or reference object to null or delete, and then perform the release action

Before doing CollectGarbage, you must be aware of two prerequisites:

Reference - An object becomes invalid outside the context in which it exists.
- A global object will become invalid if it is not used (referenced).

Copy code The code is as follows:

//------------------------------------------------ ----------
//When does a JavaScript object expire
//------------------------------------------------ ----------
function testObject() {
var _obj1 = new Object();
}
function testObject2() {
var _obj2 = new Object();
return _obj2;
}
// Example 1
testObject();
// Example 2
testObject2()
//Example 3
var obj3 = testObject2();
obj3 = null;
//Example 4
var obj4 = testObject2();
var arr = [obj4];
obj3 = null;
arr = [];

In these four examples:
- "Example 1" constructs _obj1 in the function testObject(), but when the function exits, it has left the context of the function, so _obj1 is invalid;

- In "Example 2", an object _obj2 is also constructed in testObject2() and passed out, so the object has an "outside function" context (and life cycle). However, because the return value of the function is not Other variables are "held", so _obj2 is also immediately invalid;

- In "Example 3", _obj2 constructed by testObject2() is held by the external variable obj3. At this time, until the "obj3=null" line of code takes effect, _obj2 will become invalid because the reference relationship disappears. .

- For the same reason as Example 3, _obj2 in "Example 4" will become invalid after the "arr=[]" line of code.

However, the "invalidation" of an object does not wait until it is "released". Within the JavaScript runtime environment, there is no way to tell the user exactly when an object will be released. This relies on JavaScript's memory recycling mechanism. ——This strategy is similar to the recycling mechanism in .NET.

In the previous Excel operation sample code, the owner of the object, that is, the process of "EXCEL.EXE" can only occur after the "release of the ActiveX Object instance". File locks and operating system permission credentials are process-related. So if the object is merely "invalidated" rather than "released", there will be problems for other processes handling the file and referencing the operating system's permission credentials.

——Some people say this is a BUG in JavaScript or COM mechanism. Actually no, this is caused by a complex relationship between OS, IE and JavaScript, rather than an independent problem.

Microsoft has disclosed a strategy to solve this problem: actively calling the memory recycling process.

A CollectGarbage() process (usually referred to as the GC process) is provided in (Microsoft) JScript. The GC process is used to clean up the "invalid object exceptions" in the current IE, that is, to call the object's destructor process.

The code to call the GC process in the above example is:

Copy code The code is as follows:

//------------------------------------------------ ----------
// When dealing with ActiveX Object, the standard calling method of the GC process
//------------------------------------------------ ----------
function writeXLS() {
//(omitted...)
excel.Quit();
excel = null;
setTimeout(CollectGarbage, 1);
}

The first line of code calls the excel.Quit() method to cause the excel process to terminate and exit. At this time, because the JavaScript environment holds an excel object instance, the excel process does not actually terminate.

The second line of code makes excel null to clear the object reference, thereby "invalidating" the object. However, since the object is still in the function context, if the GC process is called directly, the object will still not be cleaned up.

The third line of code uses setTimeout() to call the CollectGarbage function, and the time interval is set to '1', which only causes the GC process to occur after the writeXLS() function is executed. In this way, the excel object meets the two conditions of "can be cleaned by GC": no reference and leaving the context.

The use of GC process is very effective in JS environment using ActiveX Object. Some potential ActiveXObjects include XML, VML, OWC (Office Web Component), flash, and even VBArray in JS. From this point of view, the ajax architecture uses XMLHTTP and must also meet the "no page switching" feature. Therefore, actively calling the GC process at the appropriate time will result in a better efficient UI experience.

In fact, even if the GC process is used, the excel problem mentioned above will still not be completely solved. Because IE also caches the permission credentials. The only way to update the page's credentials is to "switch to a new page",

So in fact, in the SPS project mentioned earlier, the method I used was not GC, but the following code:

Copy code The code is as follows:

//------------------------------------------------ ----------
// Page switching code used when processing ActiveX Object
//------------------------------------------------ ----------
function writeXLS() {
//(omitted...)
excel.Quit();
excel = null;
// The following code is used to solve a BUG in IE call Excel, the method provided in MSDN:
// setTimeout(CollectGarbage, 1);
// Since the trusted status of the web page cannot be cleared (or synchronized), methods such as SaveAs() will be used in
// Invalid the next time it is called.
location.reload();
}

Description of delete operator in manual
A reference removes a property from an object, or removes an element from an array.

delete expression

The

expression parameter is a valid JScript expression, usually a property name or array element.

Description

If the result of expression is an object and the property specified in expression exists, and the object does not allow it to be deleted, return false.

In all other cases, returns true.

Finally, a supplementary note about GC: when the IE form is minimized, IE will actively call the CollectGarbage() function once. This allows the memory usage to be significantly improved after minimizing the IE window

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.