Blackbing Playground

new Object() vs {} and new Array() vs [] 效能比較

在javascript中,要new一個空的object,可以用
var foo = new Object;
或是
var foo = {};

而 要new一個空的Array,可以用
var bar = new Array();
或是
var bar = [];

我做了一個簡單的效能比較如上圖所示

結論:
new 空物件和new 空陣列只要使用{}、[]即可,簡單又快速。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<button onclick="testObj1()">testObj1</button>
<button onclick="testObj2()">testObj2</button>
<button onclick="testArray1()">testArray1</button>
<button onclick="testArray2()">testArray2</button>
<div id="bug"></div>
<script>
function testObj1(){
var current = getCurrentTime();
for(var i=0; i<100000; i++)
var obj = new Object();
document.getElementById('bug').innerHTML += "new Object:"+(getCurrentTime() - current) + "ms<br />";
}
function testObj2(){
var current = getCurrentTime();
for(var i=0; i<100000; i++)
var obj = {};
document.getElementById('bug').innerHTML += "{}:"+(getCurrentTime() - current) + "ms<br />";
}
function testArray1(){
var current = getCurrentTime();
for(var i=0; i<100000; i++)
var obj = new Array();
document.getElementById('bug').innerHTML += "new Array:"+(getCurrentTime() - current) + "ms<br />";
}
function testArray2(){
var current = getCurrentTime();
for(var i=0; i<100000; i++)
var obj = [];
document.getElementById('bug').innerHTML += "[]:"+(getCurrentTime() - current) + "ms<br />";
}
function getCurrentTime(){
return new Date().getTime();
}
</script>