4

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;
}
boyomarinov
  • 615
  • 4
  • 12

1 Answers1

3

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.

Jaycee
  • 3,098
  • 22
  • 31
  • What about in the case of non-referenced types, e.g. primitive string? However, [this answer suggests](http://stackoverflow.com/a/1308668/1481489) that `bar` will simply point to the result of `getSmth`, and not be copied in memory. – zamnuts Oct 06 '15 at 14:02
  • @zamnuts: It's definitely not copied (JavaScript sans optimization is 100% reference semantics, and optimization wouldn't make copies for fun). The only question is whether it (pointlessly) stores a local reference to the "stack" equivalent, then loads it and returns it, or whether it just returns directly. I suspect most optimizing JS engines will return directly, but even if they do, I personally prefer not pointlessly creating the named variable; just `return` directly instead of wasting lines of code on stuff that doesn't aid readability anyway. – ShadowRanger Oct 06 '15 at 22:15