Search code examples
javascriptperformanceprototypal-inheritance

Does using classes in javascript instead of constructors give a performance hit?


I'm assuming since classes in javascript are just syntax suger that class are being converted into constructor functions at some point, so I'm also assuming that his creates an extra thing for a engine to do, is this an accurate assumption?

 //Class, is this slower then a constructor   
class Employee{
    constructor(name,job,weeklyPay,age){
        this.name=name;
        this.breed=breed;
        this.age=age;
    }
    pay(){
        console.log(this.name + ": was paid " + weeklyPay);
    }
}

class Manager extends Employee{
     constructor(){
        this.reports=[];
     }
    addReport(report){
        this.report.push(report);
    }

    removeReport(index){
        this.report.splice(index,1);
    }
}

//constructor, is this more performant then a class?
function Employee(name,job,weeklyPay,age){
    this.name=name;
    this.job=job;
    this.weeklyPay=weeklyPay;
    this.age=age;
}
Employee.prototype.pay=function(){
    console.log(this.name + ": was paid " + weeklyPay);
}


function Manager(name,job,weeklyPay,age){
    Employee.call(this,name,job,weeklyPay,age);
    this.name=name;
    this.job=job;
    this.weeklyPay=weeklyPay;
    this.age=age;
    this.reports=[];
}
Manager.prototype=Object.create(Employee.prototype);

Manager.prototype.addReport=function(report){
    this.reports.push(report);
}
Manager.prototype.removeReport=function(index){
    this.reports.splice(index,1);
}

Solution

  • No, this is not accurate.

    I'm assuming since classes in javascript are just syntax suger that class are being converted into constructor functions at some point

    Not really. Both are transformed into the internal representation of functions and objects, but that happens independently.

    I'm also assuming that his creates an extra thing for a engine to do?

    No, "extra thing" implies that the class syntax would be translated into constructor function code which is then parsed as usual. This is only what happens when you are using a transpiler, but it's certainly not how an engine does it.

    Actually, the assumption should be the contrary: class syntax comes closer to the internal representation of constructor functions, by conveying the intent to be used as a class it's much easier to optimise than plain functions which need extra heuristics. It's more declarative (does not need any mutation) and is designed in the spec to be easier to compile (e.g. by implying strict mode).