boyomarinov
boyomarinov

Reputation: 615

Is there a difference between returning inner variable from function versus returning directly value

Say we have two functions, that return a large object. One returns data directly, the other assigns it to an inner variable and returns this variable. Does anybody have an idea if there would be a difference in the heap memory that would be allocated as well as in performance and why? Is the browser engine going to optimize somehow the code, so it might end up being the same?

function foo() {
    return getSmth();
}

function foo() {
    var bar = getSmth();
    return bar;
}

Upvotes: 4

Views: 204

Answers (1)

Jaycee
Jaycee

Reputation: 3118

The heap allocations are pretty much going to be the same. In the second example and assuming no optimizations, if the return value of the inner function is an object then you are copying an extra reference to bar. If the return value is a primitive type then you are copying the number of bytes used to hold the value. In either case the extra reference/value is then thrown away and in the unlikely event it was ever stored on the heap becomes available for garbage collection.

It may be the case that the javascript engine, during compilation, will optimize the bar variable away.

Upvotes: 3

Related Questions