Theoretical case. The function init () may not always be called on the page. What I want to know is if there is a difference from a speed/efficiency point of view between the two scripts? Will the fact that Class is a singleton make a difference to loading speed/amount of processing?
Script 1:
// Class is a singleton.
var Class =
{
myFunctionOne : function ()
{
}
myFunctionTwo: function ()
{
}
}
function init ()
{
//Do some fancy stuff
Class.myFunctionOne();
Class.myFunctionTwo();
}
Script 2:
function Class ()
{
this.myFunctionOne = function ()
{
}
this.myFunctionTwo = function ()
{
}
}
function init ()
{
var myClass = new Class();
//Do some fancy stuff
myClass.myFunctionOne();
myClass.myFunctionTwo();
}
I would say yes, your second script has a performance advantage when
init()is not being called on the page. Here’s why.In your first example, the object literal will be parsed each time the page is loaded:
The
Classobject will be built, each key set to a function object. This overhead will be incurred regardless of whether these “methods” are ever actually called (though, it’s possible certain JavaScript compilers may implement optimizations here such as “Just-In-Time compiling”, so the actual perf gain may vary browser to browser)In your second example:
The
myFunctionOneline is being run each timeClassis being called, in your case through thenewoperator. This cost will be incurred each timeClassis instantiated rather than once per page load. However you’ve stated this class is using a singleton pattern so you’ll only have one instance anyway.