I have been experimenting using static methods in Javascript. Instead of having objects inherit from a prototype, I use duck-typing a lot harder.
var Controller = {};
Controller.getData = function() {//return data};
// and then in use:
var page = route.getPage();
require([page], function(Controller) {
Controller.getData();
});
I could do this same by creating new objects with the Controller prototype:
function Controller() {};
Controller.prototype.getData = function() {//return data};
// and then in use:
var page = route.getPage();
require([page], function(Controller) {
var controller = new Controller();
controller.getData();
});
My gut feeling is that the static method will be faster, but I have no clue. In general, what are the performance discrepancies between these two methods?
TLDR; basically this question but for Javascript.
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
The static method can call without object while instance method can not be called without object. The execution time of instance method is faster than static method but in the PHP version 5.3 there was a bug which says that static methods are faster in which they have introduced late binding.
if it's a static method (doesn't use any instance data), then declare it as a static method and you can directly call it. If it's an instance method, then you would typically create an object of type one and then call the method on that object (usually in the constructor).
Static properties are used when we'd like to store class-level data, also not bound to an instance. The syntax is: class MyClass { static property = ...; static method() { ... } }
Edit: So there is a bit of a performance difference when you are instantiating the class vs. calling the "static" version, but the difference doesn't really warrant you making any changes to your code (premature optimization) unless you are seeing an actual slow down.
As demonstrated in the basic jsperf test I setup, there really isn't much of a difference, performance wise. You should make the decision based on whether or not you want the context (this
) to refer to your base class or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With