开发者

most efficient javascript method declaration

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 whi开发者_开发问答ch is the most efficient one? (especially between 1 and 2)

Will your answer be different if doSomething has arguments?


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.


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.


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...


you are missing the most optimized one:

var x = function(){}

When javascript sees the definition:

function x(){}

It then converts it into the former form. If you do it that way in the first place there is a negligable speed up. But for the sake of answering your question, this is the most optimal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜