In JavaScript, browsers, especially mobile browsers, have a limited amount of memory allocated, and it's a very meaningful thing to save memory. An effective way to conserve memory is to reduce the number of objects.
Enjoy meta mode (Flyweight), run the sharing technology to effectively support a large number of fine-grained objects, avoid a large number of the same content of the small class of overhead (such as memory), so that everyone share a class (meta Class).
The element mode avoids the overhead of a large number of very similar classes, in the program design, sometimes need to produce a large number of fine-grained class instances to represent the data, if you can find these instances in addition to several parameters, the cost is basically the same, you can significantly less need to instantiate the number of classes. If you can move those parameters outside of the class instance and pass them in when the method is called, you can reduce the number of individual instances by sharing drastically.
There are two ways to apply the meta pattern in JavaScript. The first is applied to the data layer, mainly in the memory of a large number of similar objects; the second is applied to the DOM layer, which can be used on the central event manager to avoid attaching event handles to every child element in the parent container
There are two important concepts in flyweight-internal state intrinsic and external state extrinsic, internal state is within the object through internal method management, and external information can be deleted or saved by the outside.
White point, is to pinch a first original model, and then with different occasions and environment, and then produce the specific characteristics of the model, it is obvious that here need to produce different new objects, so flyweight mode often appear Factory mode, flyweight internal state is used to share, Flyweight Factory is responsible for maintaining a Flyweight pool (pattern pool) to hold objects in the internal state.
We can replace all objects with the same internal state as the same shared object. To create such a shared object, you need to use a singleton factory method instead of a normal constructor, which tracks the individual objects that have already been instantiated, creating a new object only if the internal state of the desired object is different from the existing object. The external state of the object is saved in a Manager object. When you call the object's methods, the manager passes these external states as arguments.
Save one object's data in two different objects (shared objects, organizer objects)
1. Shared objects (object of privilege)
2. Single example factory method (create shared object)
3. Manager object (Admin external State)
For example, a book in a library can be represented by an object, he has many attributes
var book = function (ID, title, author, genre, Pagecount,publisherid, ISBN, Checkoutdate, Checkoutmember, Duereturndate,av ailability) {
...//Initialize code
}
book.prototype = {
gettitle:function () {return
this.title;
},
...
Update the loan status method
updatecheckoutstatus:function (BookID, NewStatus, Checkoutdate,checkoutmember, newreturndate) {...},
//Renew
extendcheckoutperiod:function (BookID, newreturndate) {...},//
whether expires
ispastdue:function ( BookID) {...}}
}
The program may be fine at first, but as time increases, books can grow in large quantities, and each book has a different version and quantity, and you will find that the system is getting slower. Thousands of book objects can be imagined in memory, we need to use the element mode to optimize.
We can divide the data into two internal and external data, in the same book, the data related to the Books object (Title,author, etc.) can be attributed to the internal property, and (Checkoutmember,duereturndate, etc.) can be attributed to the external attribute. In this way, the following code can share the same object in the same book, because no matter who borrows the book, as long as the book is the same book, the basic information is the same:
Shared Objects
var book = function (title, author, genre, PageCount, PublisherID, ISBN) {
this.title = title;
This.author = author;
this.genre = genre;
This.pagecount = PageCount;
This.publisherid = PublisherID;
This. ISBN = ISBN;
};
Let's define a base factory that checks to see if the book object was created before, and if it does, it returns without recreating and storing it so that you can continue to access it later, ensuring that we create only one object for each of these books:
/* Book Factory single case
/var bookfactory = (function () {
var existingbooks = {};
return{
createbook:function (title, author, genre,pagecount,publisherid,isbn) {/
* to find whether to create * *
var Existingbook = EXISTINGBOOKS[ISBN];
if (Existingbook) {return
existingbook;
} else{
/* If not, create one, and then save *
/var book = new (title, author, genre,pagecount,publisherid,isbn);
EXISTINGBOOKS[ISBN] = Book;
return book;
}}}
);
External state, relatively simple, in addition to our packaged book, the others need to be managed here:
/*bookrecordmanager Library Management Category * * var Bookrecordmanager = (function () {var bookrecorddatabase = {}; return{/* Add a library record * * Addbookrecord:function (ID, title, author, Genre,pagecount,publisherid,isbn, Checkoutdate, CHEC Koutmember, duereturndate, availability) {var book = Bookfactory.createbook (title, author, Genre,pagecount,publisher
ID,ISBN); Bookrecorddatabase[id] ={checkoutmember:checkoutmember, Checkoutdate:checkoutdate, DueReturnDat
E:duereturndate, availability:availability, Book:book;
}; }, Updatecheckoutstatus:function (BookID, NewStatus, Checkoutdate, Checkoutmember, newreturndate) {var record =
Bookrecorddatabase[bookid];
record.availability = NewStatus;
Record.checkoutdate = checkoutdate;
Record.checkoutmember = Checkoutmember;
Record.duereturndate = newreturndate; }, Extendcheckoutperiod:function (BookID, newreturndate) {Bookrecorddatabase[bookid].duereturNdate = newreturndate;
}, Ispastdue:function (BookID) {var currentdate = new Date ();
return Currentdate.gettime () > Date.parse (bookrecorddatabase[bookid].duereturndate);
}
};
});
In this way, we have been able to keep the same information of the same book in a Bookmanager object, and save only one copy, compared to the previous code, you can find that a lot of memory savings.
Object Pool
Object pooling is another kind of performance optimization scheme, and there are some similarities with the pattern, but there is no separation between the internal state and the external state of the process.
Universal Object Pool Implementation:
var objectpoolfactory = function (CREATEOBJFN) {
var objectpool = [];//Object pool return
{
create:function () {//Fetch Out
var obj = objectpool.length = 0 createobjfn.apply (this,arguments): Objectpool.shift ();
return obj;
},
recover:function (obj) {//retract
objectpool.push (obj);
}}}
;
Now use Objectpoolfactory to create an object pool that loads some iframe:
var iframefactory = objectpoolfactory (function () {
var iframe = document.createelement (' iframe ');
Document.body.appendChild (IFRAME);
Iframe.onload = function () {
iframe.onload = null;//Prevent Bug
iframefactory.recover (iframe) repeatedly loaded by IFRAME; After the IFRAME is loaded, the node (retract) is filled back into the object pool
.
return iframe;
});
Call
var iframe1 = Iframefactory.create ();
IFRAME1.SRC = ' http://www.qq.com ';
References: JavaScript mode "JavaScript design pattern and development practice"
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.