Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Objects vs IDs

I have a general javascript question.

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

In my functions that process persons, I usually pass the Person object I'm manipulating. However this somehow feels wrong. Like I'm wasting memory.

So my question:

  • Am I using extra memory by passing the objects instead of just their ID's?
  • Is using getPersonByID() and just passing ID's instead a better option?
  • How do you go about managing many instances of objects?
like image 789
whateverforever Avatar asked Oct 15 '16 13:10

whateverforever


3 Answers

Am I using extra memory by passing the objects instead of just their ID's?

No, you are passing a reference to the object, not a copy of it every time. So no extra memory is being used for each time you pass a person object around... So when you ask:

Is using getPersonByID() and just passing ID's instead a better option?

Not really, as you will just add the overhead of having to go through you person list and retrieve the object again.

How do you go about managing many instances of objects?

It depends on a lot of things, like scope, who is referencing, etc. I suggest you take a look at how JS garbage collection and memory management works to have a better understanding at it.

like image 110
Felipe Sabino Avatar answered Nov 04 '22 14:11

Felipe Sabino


Object "values" in JavaScript are references. Passing an object to a function passes the reference to the object, and it's no more expensive than passing a string (like the id value) or a number.

To put it another way: passing or assigning an object value does not involve making a copy of the object.

like image 39
Pointy Avatar answered Nov 04 '22 14:11

Pointy


In javascript, objects (object literals, arrays and functions) are all passed by reference. When you pass the object to a function, you don't copy it the way you usually do in C/C++. Instead you are passing a reference (Basically a second name of the object).

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

Passing an ID on the other side will be much more verbose, it actually creates extra overhead, and it's really up to you how you want to design your application.

like image 1
Noctisdark Avatar answered Nov 04 '22 15:11

Noctisdark