undefined
undefined

Reputation: 6884

JS passing the whole object to a function takes more memory

Today I learned that if for example I have an object:

var foo = {a: 1, b: { ... }}

And I pass it to a function:

function test(foo) {
  foo.b
}

It has to load the whole foo object into the function’s scope to access the b property, which increases the memory consumption.

The advice in the book is to always pass only what you need instead:

function test(b) {
   b
 }

 test(foo.b)

My question if that's is true? and why? the object is passed by reference.

Upvotes: 3

Views: 1091

Answers (2)

fubar
fubar

Reputation: 383

Nope and here's proof.

const foo = {a: 1, b: 'bar'}

function printB(obj){
    console.log(obj.b)
    setTimeout(() =>console.log(obj.b),1000)
}

// pitfall changing a object inside a function
function editB(obj){
    obj.b = `I'm just writing something to an object`
}

printB(foo)
// prints bar
editB(foo)
// after one second it prints 'I'm just writing something to an object'

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138447

It has to load the whole foo object into the function’s scope to access the b property, which increases the memory consumption.

This is just wrong. As you said

the object is passed by reference.

Thus in both cases a reference gets passed, which will consume the same memory (if it does at all).

The advice in the book is to always pass only what you need instead

That makes sense as a good practice for clean design.

Upvotes: 6

Related Questions