V
V
Vasily Loginov2015-09-29 11:33:19
JavaScript
Vasily Loginov, 2015-09-29 11:33:19

What is the best way to design objects for memory optimization?

Hi all.
You need to create elements and store them in memory for later construction of html blocks from them.
I see 2 approaches.
First

function inputClass(id)
{
this.id = id;

function log(){
console.log(this.id);
};

this.log = log;
}

Then when creating through new inputClass("first") we get an object that has:
id: "first"
log: log()
__proto__: inputClass

And the second option
function inputClass(id)
{
this.id = id;
}
inputClass.prototype.log = function log(){
console.log(this.id);
};

Then we have an object created via new inputClass("second") and having:
id: "second"
__proto__: inputClass

The log function in this case is the same for all created objects.
But in the first version, it is copied to each of the objects, and in the second, it is stored only in the prototype.
Do I understand correctly that the more objects, the more we save memory in the second case (through prototype)?
Are there any pitfalls in this situation, and are there even better ways?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-09-29
@lekbekmek

Do I understand correctly that the more objects, the more we save memory in the second case (through prototype)?

Do I understand correctly that the less space in the closet, the more things will fit into it?
Just the same, in the second case, there are fewer objects (there are fewer essentially identical functions. Yes, a function is an object). There are no pitfalls.
The other day this topic was discussed: What are the differences between these constructs in JavaScript?
__proto__ is a reference to inputClass.prototype , not the constructor itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question