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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With