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