Reputation: 1633
async function getDataFromExternalAPI(bodyPayload) {
// send request and get data.
}
var bodyPayload = {a: 1, b: {}};
await getDataFromExternalAPI(bodyPayload);
vs
await getDataFromExternalAPI({a: 1, b: {}});
What are memory implication of using the first method? First method is cleaner in terms of redablity and maintainibility but does it comes with downside ?
Upvotes: 0
Views: 534
Reputation: 707248
What are memory implication of using the first method?
Nothing worth using that to decide which way to write it (see details below)
First method is cleaner in terms of readability and maintainability but does it comes with downside ?
No downside. Choose whichever option makes the code the cleanest to read and maintain.
What if I make is const?
Making it const
won't really change its memory use here. const
is always preferred when you don't need to assign to the symbol again because that's a sometimes useful hint to the interpreter and optimizer, but it does not change the memory use in this example.
FYI, var
is pretty much never the preferred choice any more. Use let
or const
.
Objects are passed as argument as pointers. No copy of an object is made when it is passed as an argument.
Both of your code examples are just constructing an object and then passing it as an argument. The first is giving it a named symbol so that other code within this top level scope in your example could access it and its lifetime may be longer because other code in this scope could access it before it is garbage collected.
The second example is also just constructing an object and then passing it as an argument, but because it isn't a named symbol in this scope, the only place that object can be used is within the function (unless it's returned from the function somehow or passed into other lasting scopes from within the function).
Which to use is really just a matter of preferred programming style and which makes any given circumstance more readable and maintainable. In general, I would prefer the second option if the object is only used as the argument and if the object construction doesn't require many separate steps and if no other code uses the same object and if the definition is simple.
Now if the building of this object was a complicated endeavor or there was real code clarity value to applying a meaningful name to the argument object, I'd optimize the code for how clearly I could write that complicated endeavor and that would probably involve defining a symbol in the top scope and then setting properties on that object. So, I'm optimizing for whatever makes the clearest to read code because there are not meaningful memory implications between the two.
Upvotes: 1