Skip to content

Commit 1e0294c

Browse files
targosevanlucas
authored andcommitted
benchmark: add benchmark for object properties
Adds a benchmark to compare the speed of property setting/getting in four cases: - Dot notation: `obj.prop = value` - Bracket notation with string: `obj['prop'] = value` - Bracket notation with string variable: `obj[prop] = value` - Bracket notation with Symbol variable: `obj[sym] = value` PR-URL: #10949 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent c1e166a commit 1e0294c

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
method: ['property', 'string', 'variable', 'symbol'],
7+
millions: [1000]
8+
});
9+
10+
function runProperty(n) {
11+
const object = {};
12+
var i = 0;
13+
bench.start();
14+
for (; i < n; i++) {
15+
object.p1 = 21;
16+
object.p2 = 21;
17+
object.p1 += object.p2;
18+
}
19+
bench.end(n / 1e6);
20+
}
21+
22+
function runString(n) {
23+
const object = {};
24+
var i = 0;
25+
bench.start();
26+
for (; i < n; i++) {
27+
object['p1'] = 21;
28+
object['p2'] = 21;
29+
object['p1'] += object['p2'];
30+
}
31+
bench.end(n / 1e6);
32+
}
33+
34+
function runVariable(n) {
35+
const object = {};
36+
const var1 = 'p1';
37+
const var2 = 'p2';
38+
var i = 0;
39+
bench.start();
40+
for (; i < n; i++) {
41+
object[var1] = 21;
42+
object[var2] = 21;
43+
object[var1] += object[var2];
44+
}
45+
bench.end(n / 1e6);
46+
}
47+
48+
function runSymbol(n) {
49+
const object = {};
50+
const symbol1 = Symbol('p1');
51+
const symbol2 = Symbol('p2');
52+
var i = 0;
53+
bench.start();
54+
for (; i < n; i++) {
55+
object[symbol1] = 21;
56+
object[symbol2] = 21;
57+
object[symbol1] += object[symbol2];
58+
}
59+
bench.end(n / 1e6);
60+
}
61+
62+
function main(conf) {
63+
const n = +conf.millions * 1e6;
64+
65+
switch (conf.method) {
66+
case 'property':
67+
runProperty(n);
68+
break;
69+
case 'string':
70+
runString(n);
71+
break;
72+
case 'variable':
73+
runVariable(n);
74+
break;
75+
case 'symbol':
76+
runSymbol(n);
77+
break;
78+
default:
79+
throw new Error('Unexpected method');
80+
}
81+
}

0 commit comments

Comments
 (0)