Home Web Front-end JS Tutorial JavaScript avoids memory leaks and memory management tips_javascript tips

JavaScript avoids memory leaks and memory management tips_javascript tips

May 16, 2016 pm 04:36 PM
javascript memory leak Memory management Skill

The examples in this article describe JavaScript's memory leak avoidance and memory management techniques, which are very practical. Share it with everyone for your reference. The specific method is as follows:

The content of this article comes from Google WebPerf (London WebPerf Group), August 26, 2014.

Generally speaking, efficient JavaScript web applications must be smooth and fast. Any application that interacts with users needs to consider how to ensure that memory is used efficiently, because if too much is consumed, the page will crash, forcing the user to reload. And you can only hide in the corner and cry.

Automatic garbage collection is no substitute for effective memory management, especially in large, long-running web applications. In this article, we will demonstrate how to effectively manage memory through Chrome's DevTools.

And learn how to fix performance issues like memory leaks, frequent garbage collection pauses, and overall memory bloat, the stuff that's really killing you.

Addy Osmani showed many examples of memory leaks in Chrome V8 in his PPT:

1) Deleting the properties of an Object will slow down the object (consuming 15 times more memory)

var o = { x: 'y' };
delete o.x; //此时o会成一个慢对象
o.x; //
 
var o = { x: 'y' };
o = null; //应该这样

Copy after login

2) Closure

When a variable outside the closure is introduced in the closure, the object cannot be garbage collected (GC) when the closure ends.

var a = function() {
 var largeStr = new Array(1000000).join('x');
 return function() {
  return largeStr;
 }
}();

Copy after login

3) DOM leak

When the original COM is removed, the child node reference cannot be recycled unless it is removed.

var select = document.querySelector;
var treeRef = select('#tree');
 
//在COM树中leafRef是treeFre的一个子结点
var leafRef = select('#leaf'); 
var body = select('body');
 
body.removeChild(treeRef);
 
//#tree不能被回收入,因为treeRef还在
//解决方法:
treeRef = null;
 
//tree还不能被回收,因为叶子结果leafRef还在
leafRef = null;
 
//现在#tree可以被释放了。

Copy after login

4) Timers leakage

Timers are also a common place where memory leaks occur:

for (var i = 0; i < 90000; i++) {
 var buggyObject = {
  callAgain: function() {
   var ref = this;
   var val = setTimeout(function() {
    ref.callAgain();
   }, 90000);
  }
 }
 
 buggyObject.callAgain();
 //虽然你想回收但是timer还在
 buggyObject = null;
}

Copy after login

5) Debug memory

Chrome’s built-in memory debugging tool can easily check memory usage and memory leaks:

Click record in Timeline -> Memory:

I hope this article will be helpful to everyone’s learning of javascript programming.

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ object layout is aligned with memory to optimize memory usage efficiency C++ object layout is aligned with memory to optimize memory usage efficiency Jun 05, 2024 pm 01:02 PM

C++ object layout and memory alignment optimize memory usage efficiency: Object layout: data members are stored in the order of declaration, optimizing space utilization. Memory alignment: Data is aligned in memory to improve access speed. The alignas keyword specifies custom alignment, such as a 64-byte aligned CacheLine structure, to improve cache line access efficiency.

Golang function memory leak detection and resolution Golang function memory leak detection and resolution Apr 23, 2024 pm 05:09 PM

There is a function memory leak in the Go language, which will cause the application to continuously consume memory and crash. We can use the runtime/pprof package for detection and check if a function accidentally holds a reference to an unneeded resource. To solve a memory leak, we need to find the reference that caused the leak, usually by inspecting the function code and looking for global variables or closure references.

C++ Memory Management: Custom Memory Allocator C++ Memory Management: Custom Memory Allocator May 03, 2024 pm 02:39 PM

Custom memory allocators in C++ allow developers to adjust memory allocation behavior according to needs. Creating a custom allocator requires inheriting std::allocator and rewriting the allocate() and deallocate() functions. Practical examples include: improving performance, optimizing memory usage, and implementing specific behaviors. When using it, you need to pay attention to avoid freeing memory, manage memory alignment, and perform benchmark tests.

Challenges and countermeasures of C++ memory management in multi-threaded environment? Challenges and countermeasures of C++ memory management in multi-threaded environment? Jun 05, 2024 pm 01:08 PM

In a multi-threaded environment, C++ memory management faces the following challenges: data races, deadlocks, and memory leaks. Countermeasures include: 1. Use synchronization mechanisms, such as mutexes and atomic variables; 2. Use lock-free data structures; 3. Use smart pointers; 4. (Optional) implement garbage collection.

How to manage memory usage in PHP functions? How to manage memory usage in PHP functions? Apr 26, 2024 pm 12:12 PM

To manage memory usage in PHP functions: avoid declaring unnecessary variables; use lightweight data structures; release unused variables; optimize string processing; limit function parameters; optimize loops and conditions, such as avoiding infinite loops and using indexed arrays .

Reference counting mechanism in C++ memory management Reference counting mechanism in C++ memory management Jun 01, 2024 pm 08:07 PM

The reference counting mechanism is used in C++ memory management to track object references and automatically release unused memory. This technology maintains a reference counter for each object, and the counter increases and decreases when references are added or removed. When the counter drops to 0, the object is released without manual management. However, circular references can cause memory leaks, and maintaining reference counters increases overhead.

How does C++ memory management interact with the operating system and virtual memory? How does C++ memory management interact with the operating system and virtual memory? Jun 02, 2024 pm 09:03 PM

C++ memory management interacts with the operating system, manages physical memory and virtual memory through the operating system, and efficiently allocates and releases memory for programs. The operating system divides physical memory into pages and pulls in the pages requested by the application from virtual memory as needed. C++ uses the new and delete operators to allocate and release memory, requesting memory pages from the operating system and returning them respectively. When the operating system frees physical memory, it swaps less used memory pages into virtual memory.

Best practices for memory management of golang functions Best practices for memory management of golang functions Apr 26, 2024 pm 05:33 PM

Memory management best practices in Go include: avoiding manual allocation/freeing of memory (using a garbage collector); using memory pools to improve performance when objects are frequently created/destroyed; using reference counting to track the number of references to shared data; using synchronized memory pools sync.Pool safely manages objects in concurrent scenarios.

See all articles