1

I have two versions of the code. Can someone let me know which is optimal and faster?

Version 1:

function showMsg(a)
{
    alert(a);
}
function invokeShowMsg()
{
    var msg = 'hi';
    showMsg(msg);
}
window.setTimeout(invokeShowMsg,1000);

Version 2:

function showMsg(a)
{
    alert(a);
}
window.setTimeout(function(){showMsg('hi');},1000);

One more doubt, is the Version 2 way of calling called "Closure"?

thandasoru
  • 1,558
  • 2
  • 15
  • 41
  • What are your criteria for "optimal"? I suspect #1 is faster because it passes a reference to an already declared function rather than evaluating a function expression and passing a reference to that—but you should test it in various browsers. In any case, if execution is delayed by a minimum of 1 second, of what relevance is speed? – RobG Jan 23 '12 at 04:44
  • Since I run it in a Mobile browser, will version 2 cause any adverse impact? – thandasoru Jan 23 '12 at 04:51
  • You will not notice it, even if you tried. Most* JS engines compile the code. – Blender Jan 23 '12 at 04:56

3 Answers3

4

As far as speed goes, you will not notice any difference between the two whatsoever, so pick what you like.

I prefer #2, as it is cleaner and keeps the syntax readable:

setTimeout(function() {
  showMsg('hi');
}, 1000);
Blender
  • 289,723
  • 53
  • 439
  • 496
  • [Is it really a closure](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)? – voithos Jan 23 '12 at 04:50
  • I just say yes because it makes no difference whatsoever to me, as I haven't really found a practical use for distinguishing an anonymous function and a closure (even if I use both). – Blender Jan 23 '12 at 04:53
  • 2
    But +1 for actually knowing the answer. I retract my statement in shame. – Blender Jan 23 '12 at 04:55
3

Yes , version 2 is called Closure. As far as speed, they are both equivalent.

ozczecho
  • 8,649
  • 8
  • 36
  • 42
  • Thanks, I read somewhere in Google's pages where it said version 2 (closure) is slower than version 1. I used version 2 all over my code and I don't really want to change it now.. – thandasoru Jan 23 '12 at 04:42
2

As @Blender said, I also prefer 2, as it doesn't pollute the global space with (semi-useless) "caller" functions. It's clean, and it simple to understand to someone who knows how setTimeout works. And as far as speed goes, there's virtually no difference. Here's a performance comparison of the two methods.

However, as far as I understand, it is not a closure. It is simply an anonymous function. In JavaScript, as in many other dynamic language, functions are first class citizens, meaning that they can be created and passed around- they are objects. However, a closure is more than just an anonymous function. The answers to this question explain what a closure is quite succinctly.

Community
  • 1
  • 1
voithos
  • 68,482
  • 12
  • 101
  • 116