What is the difference between `new Object()` and object literal notation?

前端 未结 11 959
北恋
北恋 2020-11-22 07:41

What is the difference between this constructor-based syntax for creating an object:

person = new Object()

...and this literal syntax:

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:32

    On my machine using Node.js, I ran the following:

    console.log('Testing Array:');
    console.time('using[]');
    for(var i=0; i<200000000; i++){var arr = []};
    console.timeEnd('using[]');
    
    console.time('using new');
    for(var i=0; i<200000000; i++){var arr = new Array};
    console.timeEnd('using new');
    
    console.log('Testing Object:');
    
    console.time('using{}');
    for(var i=0; i<200000000; i++){var obj = {}};
    console.timeEnd('using{}');
    
    console.time('using new');
    for(var i=0; i<200000000; i++){var obj = new Object};
    console.timeEnd('using new');
    

    Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

    my output was the following:

    Testing Array:
    using[]: 1091ms
    using new: 2286ms
    Testing Object:
    using{}: 870ms
    using new: 5637ms
    

    so clearly {} and [] are faster than using new for creating empty objects/arrays.

提交回复
热议问题