JavaScript also talk about memory optimization

Source: Internet
Author: User
Tags event listener tmlp

In contrast to C + +, the use of JavaScript in memory has allowed us to focus more on the writing of business logic in development. But as business continues to complicate the development of single-page applications, mobile HTML5 applications, and node. JS programs, memory problems in JavaScript are no longer familiar. This article explores the use and optimization of memory from the language level of JavaScript. From the familiar or slightly heard aspects, to the majority of people will not notice the place, we analyze each. 1. Memory management at the language level 1.1 scope scope is a very important operating mechanism in JavaScript programming, it does not fully arouse the attention of beginners in the programming of synchronous JavaScript, but in asynchronous programming, Good scope control skills have become an essential skill for JavaScript developers. In addition, scopes play a critical role in JavaScript memory management. In JavaScript, there are function calls, with statements, and global scopes that can form a scope. For example, the following code: Copy the Code as follows: var foo = function () {var local = {};}; Foo (); console.log (local); = = Undefinedvar Bar = function () {local = {};}; Bar (); Console.log (local); = = {} Here we define the Foo () function and the bar () function, all of which are intended to define a variable named Local. But the end result was quite different. In the Foo () function, we use the VAR statement to declare that a local variable is defined, and because a scope is formed inside the function body, the variable is defined in that scope. and the Foo () function does not have any scope extension processing in the body, so when the function is finished, the local variable is destroyed. The variable cannot be accessed in the outer scope. Within the bar () function, the local variable is not declared with the Var statement, instead it is defined directly as a global variable. Therefore, the outer scope can be accessed to this variable. Copy the code as follows: Local = {};//The definition here is equivalent to global.local = {};1.2 scope chain in JavaScript programming, you are bound to encounter multiple layers of function nesting scenarios, which is the typical representation of the scope chain. As shown in the following code: the copy Code code is as follows: function foo (){var val = ' Hello ';    function bar () {function Baz () {global.val = ' world; ')    } baz (); Console.log (Val); = = Hello} bar ();} Foo (); Based on the previous description of the scope, you might think that the code here shows the result of world, but the actual result is hello. A lot of beginners will start to feel confused here, so let's look at how this piece of code works. Because of JavaScript, the lookup of a variable identifier is looked out from the current scope until the global scope. So access to variables in JavaScript code can only be done outward, not on the reverse line. The execution of the Baz () function defines a global variable Val in the global scope. In the bar () function, when accessing the Val identifier, it is found in the scope of the last layer, the Foo () function, according to the internal-to-foreign de-lookup principle: It is not located in the scope of the bar function. However, the key to the confusion is here: This identifier access does not continue to look out for the matching variable found in the scope of the Foo () function, so the global variable Val defined in the Baz () function does not have an impact in this variable access. 1.3 Closures We know that identifier lookups in JavaScript follow the principles from inside out. But with the complexity of business logic, the single delivery order is far from meeting the increasing demand.  Let's take a look at the following code: Copy the Code as follows: function foo () {var local = ' Hello ';  return function () {return local; };} var bar = foo (); Console.log (bar ()); The technique shown here to let the outer scope access the inner scope is closure (Closure). The scope of the Foo () function is "extended", thanks to the application of higher-order functions. The Foo () function returns an anonymous function that exists within the scope of the Foo () function, so you can access the local variable within the scope of the Foo () function and save its reference. Because this function returns the local variable directly, the bar () function can be executed directly in the outer scope to obtain the local variable. Closures are a high-level feature of JavaScript, and we can use it to achieve more complex effects to meet different needs. But it's important to note that theThe function referenced by the internal variable takes out the outside of the function, so the variable within the scope is not necessarily destroyed after the function is executed, until the reference to the internal variable is completely dismissed. Therefore, the application of closures can easily cause memory to be unable to release the situation. 2. JavaScript memory recovery mechanism Here I will use chrome and node. js, the Google-launched V8 engine, for example, a brief introduction of JavaScript memory recycling mechanism, more detailed content can buy my good friend Pauling's book The "Memory Control" chapter has a fairly detailed introduction to the learning of node. js. In V8, all JavaScript objects are allocated in memory through "heap". When we declare a variable in code and assign a value, V8 allocates a portion of it to the variable in the heap memory. If the requested memory is not sufficient to store the variable, V8 continues to request memory until the heap reaches the V8 memory limit. By default, the maximum heap memory size of V8 is 1464MB in 64-bit systems and 732MB in 32-bit systems, which is about 1.4GB and 0.7GB. In addition, V8 manages the generation of JavaScript objects in heap memory: Cenozoic and Laosheng. The new generation is a short-lived JavaScript object, such as temporary variables, strings, and so on, whereas the Laosheng generation is a long-lived object, such as host controller, server object, and so on, which has survived multiple garbage collection. is the garbage collection algorithm always important in the development of programming languages? , and the garbage collection algorithm used in V8 has the following main types: 1. Scavange algorithm: Memory space management by means of replication, mainly used in the new generation of memory space; 2. Mark-sweep algorithm and mark-compact algorithm: The heap memory is organized and recycled by tags, which is mainly used for checking and recycling of Laosheng objects. PS: More detailed V8 garbage collection implementations can be learned by reading related books, documents, and source code. Let's look at the circumstances under which the JavaScript engine will recycle which objects. 2.1 Scope and Reference beginners often assume that when a function is finished, the objects declared inside the function are destroyed. But in fact this understanding is not rigorous and comprehensive, it is easy to cause confusion. Reference (Reference) is a very important mechanism in JavaScript programming, but it is strange that the average developer will not intentionally notice it or even know it. A reference is a "code-to-object access" abstract relationship, which is somewhat similar to the pointer to C + +, but not the same thing. References are also one of the most critical mechanisms of the JavaScript engine in garbage collection. Take the following code as an example: Copy codeThe code is as follows://... var val = ' Hello World '; function foo () {return function () {return val; };} Global.bar = foo ();//... After reading this code, can you say that this part of the code after execution, which objects are still alive? According to the relevant principle, the object in this code that has not been reclaimed is the Val and bar (), what is the reason why they cannot be recycled? How is the JavaScript engine garbage collected? The garbage collection algorithm mentioned earlier is only used for recycling, so how does it know which objects can be recycled and which ones need to survive? The answer is a reference to a JavaScript object. In JavaScript code, even if you simply write down a variable name as a single row without doing anything, the JavaScript engine will assume that this is an access behavior for the object, and there is a reference to the object. To ensure that the behavior of garbage collection does not affect the operation of the program logic, the JavaScript engine must not be able to recycle the objects being used, or it will be out of order. So judging whether the object is in use is the standard, whether there is still a reference to the object. But in fact, this is a compromise, because JavaScript references can be transferred, it is possible that some references are brought to the global scope, but in fact, in the business logic has no need to access it, should be recycled, but JavaScript The engine will still be inflexible to think that the program still needs it. How to use variables and references in the right posture is the key to optimizing JavaScript from a language level. 3. Optimize your JavaScript finally get to the point, thank you for your patience to see here, after so many introductions above, I believe you have a good understanding of the memory management mechanism of JavaScript, then the following techniques will give you a more powerful. 3.1 Use of functions if you have the habit of reading good JavaScript projects, you will find that many of them often use an anonymous function to package the outermost layer of code when developing the front-end JavaScript code. Copy the Code as follows: (function () {//main business code}); Some even more advanced: Copy code code as follows:;(function (Win, Doc, $, undefined) {//main business code}) (Window, documen T, JQuery); Even the front-end modular loading solution, such as Requirejs, Seajs, Ozjs,Are all in a similar form: Copy code code as follows://Requirejsdefine ([' jquery '], function ($) {//main business code});//Seajsdefine (' m?? Odule ', [' dep ', ' underscore '], function ($, _) {//main business code}); If you say that many of the code for the node. JS Open source project is not handled this way, you are wrong. node. js, before actually running the code, wraps each. js file into the following form: The copy Code code is as follows: (function (exports, require, module, __dirname, __filename) {//main business generation code}); What good is this? We all know that at the beginning of the article, there are function calls, with statements, and global scopes that can form scopes in JavaScript. And we also know that the object that is defined in the global scope is likely to survive until the process exits, and if it is a large object, it will be troublesome.  For example, some people like to do template rendering in javascript: Copy code code as follows: <?php $db = mysqli_connect (server, user, password, ' MyApp '); $topics = Mysqli_query ($db, "select * from topics;");? ><!doctype html>

JavaScript also talk about memory optimization

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.