What's the differences, pros, or cons of
var obj = {};
VS
var obj = new Object();
All I know is that the second example takes longer. Is there any real benefit?
** EDIT **
function loop() {
var start = (new Date()).getTime();
for(var i = 0; i < 1000000; ++i) {
//var b = {}; // takes ~548ms on my machine
var b = new Object(); // takes ~287ms on my machine
}
trace((new Date()).getTime() - start);
setTimeout(loop, 1);
}
loop();
If you switch between var b = {};
and var b = new Object();
You'll see the performance differences. They are opposite from my recollection and what I mentioned in the question.
As far as I'm aware, they are equivalent. By "the second example takes longer", I assume you mean only in time to type the statement, and maybe a probably immeasurable amount of time to evaluate - but the execution time should be equivalent.
Some testing tells me that new Object()
is a fair percentage quicker, though this is only in comparison to the {}
syntax, not to the abundance of any other tasks you might want to do.
The testing function:
function time(amount:int, test:Function):Number
{
var average:Number = 0;
var averages:Array = [];
for(var n:int = 0; n<amount; n++)
{
var start:Number = getTimer();
test();
averages[averages.length] = getTimer() - start;
}
for each(var a:Number in averages) average += a;
return average / averages.length;
}
Then our two test subjects:
function short():void
{
for(var i:int = 0; i<1000000; i++) var obj:Object = {};
}
function long():void
{
for(var i:int = 0; i<1000000; i++) var obj:Object = new Object();
}
And the results:
trace(time(5, short)); // 278.6
trace(time(5, long)); // 153.6
There's roughly a 45% speed increase using new Object()
, but you'll notice that the total time is still unnoticeable (even for 1,000,000 iterations).
Personally I'm still going to stick to the {}
syntax for simplicity and tidiness amongst other personal preference reasons.
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