Passing objects against identifiers

I have a general javascript question.

Let's say I have an array of persons of Person objects. Each Person has an identifier, names, addresses, etc.

In my functions that persons process, I usually pass a Person object that I manipulate. However, this is somehow not the case. It's like I'm losing my memory.

So my question is:

  • Am I using extra memory by passing objects, not just their identifiers?
  • Uses getPersonByID () and is it better to use a transfer identifier instead?
  • How can you manage many instances of objects?
+6
source share
3 answers

Am I using extra memory by passing objects, not just their identifiers?

No, you pass a link to the object, not a copy of it every time. Thus, no extra memory is used for every moment you pass the person object around ... So, when you ask:

Uses getPersonByID () and instead of just passing an identifier?

Not really, because you just add overhead to go through your people list and return the item again.

How can you manage many instances of objects?

It depends on a lot of things, such as scope, who is referenced, etc. I suggest you take a look at how JS garbage collection and memory management work in order to better understand it.

+4
source

Object "values" in JavaScript are links. Passing an object to a function passes a reference to the object, and it is no more expensive than passing a string (for example, the id value) or a number.

In other words: passing or assigning an object value does not include a copy of the object.

+2
source

In javascript, objects (object literals, arrays, and functions) are passed by reference. When you pass an object to a function, you are not copying it as usual in C / C ++. Instead, you pass a link (basically the middle name of the object).

 function func(object) { object.changed = true; } let a = {}; func(a); console.log(a.changed); //true 

Passing the identifier on the other hand will be much more verbose, it actually creates additional overhead, and it really depends on you how you want to develop your application.

+1
source

All Articles