2

Can someone explain me what are the differences between those two functions below?

I'm wondering if JavaScript engines do some kind of nano-optimizations here.

function withoutVar() {                                                                                                                   
  return 'stackoverflow';                                                                                                                    
}
function withVar() {
  var result = 'stackoverflow';
  return result;
}
var a = withoutVar();
var b = withVar();  
François Beaufort
  • 4,843
  • 3
  • 29
  • 38
  • i think there is no real difference, the variable get's cleaned up after the return and it will have practically no effect on the execution-speed. You are just saving one needless var. – Christoph Nov 06 '12 at 13:19
  • Both do the same thing. No closures were introduced. No "lost references". You just added a few more characters to the code and that's about it. – Joseph Nov 06 '12 at 13:19
  • 3
    ["This brings to mind a Bill Murray quote from Meatballs: It just doesn't matter! It just doesn't matter!"](http://www.codinghorror.com/blog/2005/01/micro-optimization-and-meatballs.html) – jbabey Nov 06 '12 at 13:21

2 Answers2

7

Some engines may perform such an optimisation. The Google Closure compiler certainly does so:

function withVar(){return"stackoverflow"}var a=withVar();

There will be virtually no difference in speed, but the "optimised" version is shorter (and therefore quicker for the client to download). Here's the results of a benchmark:

enter image description here

You can see that the "flat" version (without the variable declaration) is marginally faster (but look at the operations per second - this is an optimisation that's not even worth thinking about in terms of speed).

James Allardice
  • 164,175
  • 21
  • 332
  • 312
4

The difference is that your function withVar causes the implementation to access the underlaying Activation Object respectively Lexical Environment Record. So technically, this function will run slower, but we are not even talking about micro optimizations, more like nano optimizations.

Some browsers might indeed optimize that code into the direct return statement for withVar. Webkit or at least Chrome with their V8 engine are good candidates for that. Either way, again, this is entirely trivial and you should not be concerned about run-time performance here.

JSPerf benchmark

Difference on my machine (Chrome) is about 0.32% on ~7.000.000 calls.


The only argument I would consider to buy on stuff like this is, that the former function works with less characters. In that way, you can optimize your filesize and reduce traffic over the wire (but even then, we would have to optimize such statements on many instances before it really comes into play)

jAndy
  • 231,737
  • 57
  • 305
  • 359