6

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?
  • 1
    In JS you are not passing the object you are passing a reference to the object so no big deal on memory matters. – Redu Oct 15 '16 at 13:56
  • Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/q/518000/1529630) – Oriol Oct 16 '16 at 19:44

3 Answers3

5

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.

Felipe Sabino
  • 17,825
  • 6
  • 78
  • 112
2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

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.

Noctisdark
  • 350
  • 3
  • 17