Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript static methods vs prototypal/instatiated methods on performance

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.

like image 969
eatonphil Avatar asked May 22 '15 18:05

eatonphil


People also ask

Does static methods improve performance?

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.

Is static method faster than instance method?

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.

What is the difference between static method and instance method in JavaScript?

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

When should a property be static?

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() { ... } }


1 Answers

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.

like image 99
Rob M. Avatar answered Sep 30 '22 19:09

Rob M.