Search code examples
javascriptclassoverhead

Javascript overhead associated with Class versus object


I was wondering if the overhead associated with creating a new class instead of a new object of that class was small or large. I am using dojo, but I will provide versus examples for pure JS. I will be creating between 10 and 100 objects once at start up, I don't think this will be a serious issue, but I want to cover all my bases.

Case 1: Javascript object

function Person(name){
  this.name = name;
}
var p1 = new Person('Caine');
var p2 = new Person('Seth');
var p3 = new Person('Abel');

Versus Case 2: Javascript Classes

function Person1(){
  this.name = 'Caine';
}

function Person2(){
  this.name = 'Seth';
}

function Person3(){
  this.name = 'Abel';
}
var p1 = new Person1();
var p2 = new Person2();
var p3 = new Person3();

EDIT : people want to know why I would ever take this approach. I'm implementing a modular program where the user creates and/or loads objects as desired, and rather than having one Person/Shape/Text... class and calling it with 50,000,000 arguments (name, age, sex, label, font, x , y , w , h...) I want to create a single class with all the values. This will also simplify editing the code as I want to allow the user to view and modify the code from within the browser. I am not new to OOP, and I do realize this is a departure from standard programing procedure, so have a little faith in that i know what i am doing =)


Solution

  • Not really classes as such (JS doesn't have 'em), but what you've got in the second example is two additional constructor functions. Each will necessarily have an additional prototype property object of its own.

    So your second approach is marginally less efficient in terms of objects created and stored. If you had lots of instances of Person1, though, the second approach could save (a tiny amount of) space by putting the shared property on the prototype instead of separately on each new instance:

    function Person1() {}
    Person1.prototype.name= 'Caine';
    

    saving one String instance per Person1 instance.

    In reality it's not going to make any practical difference and you should write whichever is the cleanest expression of the idea your code encapsulates. (Personally I think it'd be unusual to have a different class for each first name...)