Is there any memory performance benefit when assigning a function to a prototype in Javascript?

I read that adding functions to an object will digest more memory and then add functions to the prototype of the object.

function Obj() {
    this.M = function() { // do something };
}

var o = new Obj();

The idea was that for each Obj construct, a new function is created and applied to Obj, which increases memory usage. For 1000 instances of Obj, you need to create 1000 functions.

function Obj() {

}
Obj.prototype.M = function() { // do something };

var o = new Obj();

For 1000 instances of Obj, in this case only one function is created. Grid of overall memory saving 999 * sizeof (M).

Is this really so? If so, then in which category does the following fall under:

function Obj() {
    Obj.prototype.M = function() { // do something };
}
var o = new Obj();

, Obj . , , N N .

-, , .

+3
2
function Obj() {
    Obj.prototype.M = function() { // do something };
}
var o = new Obj();

, , . , ... - , - M() , Obj:

function Obj(name)
{
  Obj.prototype.M = function() { alert("Hello, " + name); }
}

var shog = new Obj("shog");
var josh = new Obj("josh");

shog.M(); // alerts, "Hello, josh"
josh.M(); // alerts, "Hello, josh"

, ...
  

. :

+2

, . , (, ). , , ,

0

Source: https://habr.com/ru/post/1761206/


All Articles