Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Constructor function vs Object Initializer speed

Is there any difference between the run speeds of a constructor function when compared to an equivalent object initializer?

For example

function blueprint(var1, var2){
    this.property1 = var1;
    this.property2 = var2;
}

var object1 = new blueprint(value1,value2);

vs

object1 = {property1:value1, property2:value2};

If there is, is it relevant enough to be of concern when optimizing code or would file size take priority?

like image 815
Aron Maguire Avatar asked Mar 01 '26 06:03

Aron Maguire


2 Answers

Ran in console:

function blueprint(var1, var2){
    this.property1 = var1;
    this.property2 = var2;
}

var start = new Date();
var stop;
var object1;
for (var i = 0; i < 1000000; i++) {
    object1 = new blueprint(1,1);
}
stop = new Date();
console.log(stop - start);

Results...

 Google Chrome: 2832 milliseconds

Firefox 3.6.17: 3441 milliseconds

Ran in console:

var start = new Date();
var stop;
var object1;
for (var i = 0; i < 1000000; i++) {
    object1 = {
        'property1': 1,
        'property2': 1
    };
}
stop = new Date();
console.log(stop - start);

Results...

 Google Chrome: 2302 milliseconds

Firefox 3.6.17: 2285 milliseconds

Offhand, it's pretty obvious which one is faster. However, unless you are going through a significant amount of operations I think you should use whatever is more readable and not worry about it.

like image 102
pete Avatar answered Mar 03 '26 18:03

pete


If there is, is it relevant enough to be of concern when optimizing code or would file size take priority?

Neither.

It's extremely rare for decisions like this to have any (positive) effect on the system performance. Even if current browsers (or whatever your execution environment) show an observable advantage one way or another, that difference is not terribly likely to persist over new releases.

"It's much easier to optimize correct code than to correct optimized code."

Write readable, maintainable code and when it is all correct, check to see whether it is objectionably slow or the files are unreasonably large and make the optimizations.

like image 43
Michael Lorton Avatar answered Mar 03 '26 18:03

Michael Lorton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!