views:

62

answers:

3

While writing javascript, one can define a method in 3 different ways.

1] A function in global namespace

function doSomething();

2] A function that is member of a function

function Clazz() {}
Clazz.doSomething = function(){};

3] A function that is memeber of the instance of function

function Clazz() {}
Clazz.prototype.doSomething = function(){};

Depending upon the code organization, one can choose one of the above methods over others.

But purely from performance standpoint which is the most efficient one? (especially between 1 and 2)

Will your answer be different if doSomething has arguments?

A: 

None of those declarations do the same thing and aren't interchangeable, what kind of comparison do you expect? It's like asking if it's faster to instantiate 10 variables or an array with 10 items: one is fastest, but the result is not the same.

Jesse Dhillon
A: 

You cannot compare performance between the function declarations,

For example add(a,b) functions declared in all the 3 places give the same performance. performance matters by how you write your code, not by where you declare your functions...

Cheers

Ramesh Vel
scope chain does matter
Lauri
+1  A: 

From a pure performance POV, 1 should be the fastest. The reason being that it would require less work to setup the scope chain & execution context. Also if you access any global variables from within the function, the resolution will be fastest with 1, again simply because of the depth of scope chain. As a general rule further up (near to the global) an object is in the scope, the faster it is. for the same reason accessing property a.b will be faster than accessing a.b.c

The performance gain might not be too much in case of a simple function call, however it can mount up if say you call the function n a loop.

Gunjan
This is not entirely correct. The global scope is slower than a local scope.
bluesmoon