-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patharray-vs-object.js
91 lines (77 loc) · 1.82 KB
/
array-vs-object.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* A test to check if it is faster to
* create and acess an array with 2 elements
* or an object with 2 properties.
* The output of this test determines
* the return type of pushAtSortPosition()
*/
const pos = 23;
const ar = new Array(100).fill(0).map(() => ({
a: new Date().getTime(),
b: new Date().getTime(),
c: new Date().getTime(),
}));
function getArray() {
return [ar, pos];
}
function getObject() {
return {
array: ar,
position: pos
};
}
const totalRuns = 1000;
let done = 0;
let totalAr = 0;
let totalObj = 0;
while (done < totalRuns) {
done++;
const runs = 10000000;
let t = 0;
let time = performance.now();
if (done % 2 === 0) {
// test object
time = performance.now();
t = 0;
while (t < runs) {
t++;
getObject().array;
getObject().postition;
}
time = performance.now() - time;
totalObj = totalObj + time;
// test array
time = performance.now();
t = 0;
while (t < runs) {
t++;
getArray()[0];
getArray()[1];
}
time = performance.now() - time;
totalAr = totalAr + time;
} else {
// test array
time = performance.now();
t = 0;
while (t < runs) {
t++;
getArray()[0];
getArray()[1];
}
time = performance.now() - time;
totalAr = totalAr + time;
// test object
time = performance.now();
t = 0;
while (t < runs) {
t++;
getObject().array;
getObject().postition;
}
time = performance.now() - time;
totalObj = totalObj + time;
}
}
console.log('totalAr: ' + totalAr);
console.log('totalObj: ' + totalObj);