1'use strict'; 2 3const common = require('../common.js'); 4const assert = require('assert'); 5 6const bench = common.createBenchmark(main, { 7 method: [ 8 'object', 'nullProtoObject', 'nullProtoLiteralObject', 'storageObject', 9 'fakeMap', 'map', 10 ], 11 n: [1e6] 12}); 13 14function runObject(n) { 15 const m = {}; 16 bench.start(); 17 for (let i = 0; i < n; i++) { 18 m[`i${i}`] = i; 19 m[`s${i}`] = String(i); 20 assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); 21 m[`i${i}`] = undefined; 22 m[`s${i}`] = undefined; 23 } 24 bench.end(n); 25} 26 27function runNullProtoObject(n) { 28 const m = Object.create(null); 29 bench.start(); 30 for (let i = 0; i < n; i++) { 31 m[`i${i}`] = i; 32 m[`s${i}`] = String(i); 33 assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); 34 m[`i${i}`] = undefined; 35 m[`s${i}`] = undefined; 36 } 37 bench.end(n); 38} 39 40function runNullProtoLiteralObject(n) { 41 const m = { __proto__: null }; 42 bench.start(); 43 for (let i = 0; i < n; i++) { 44 m[`i${i}`] = i; 45 m[`s${i}`] = String(i); 46 assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); 47 m[`i${i}`] = undefined; 48 m[`s${i}`] = undefined; 49 } 50 bench.end(n); 51} 52 53function StorageObject() {} 54StorageObject.prototype = Object.create(null); 55 56function runStorageObject(n) { 57 const m = new StorageObject(); 58 bench.start(); 59 for (let i = 0; i < n; i++) { 60 m[`i${i}`] = i; 61 m[`s${i}`] = String(i); 62 assert.strictEqual(String(m[`i${i}`]), m[`s${i}`]); 63 m[`i${i}`] = undefined; 64 m[`s${i}`] = undefined; 65 } 66 bench.end(n); 67} 68 69function fakeMap() { 70 const m = {}; 71 return { 72 get(key) { return m[`$${key}`]; }, 73 set(key, val) { m[`$${key}`] = val; }, 74 get size() { return Object.keys(m).length; }, 75 has(key) { return Object.prototype.hasOwnProperty.call(m, `$${key}`); } 76 }; 77} 78 79function runFakeMap(n) { 80 const m = fakeMap(); 81 bench.start(); 82 for (let i = 0; i < n; i++) { 83 m.set(`i${i}`, i); 84 m.set(`s${i}`, String(i)); 85 assert.strictEqual(String(m.get(`i${i}`)), m.get(`s${i}`)); 86 m.set(`i${i}`, undefined); 87 m.set(`s${i}`, undefined); 88 } 89 bench.end(n); 90} 91 92function runMap(n) { 93 const m = new Map(); 94 bench.start(); 95 for (let i = 0; i < n; i++) { 96 m.set(`i${i}`, i); 97 m.set(`s${i}`, String(i)); 98 assert.strictEqual(String(m.get(`i${i}`)), m.get(`s${i}`)); 99 m.set(`i${i}`, undefined); 100 m.set(`s${i}`, undefined); 101 } 102 bench.end(n); 103} 104 105function main({ n, method }) { 106 switch (method) { 107 case 'object': 108 runObject(n); 109 break; 110 case 'nullProtoObject': 111 runNullProtoObject(n); 112 break; 113 case 'nullProtoLiteralObject': 114 runNullProtoLiteralObject(n); 115 break; 116 case 'storageObject': 117 runStorageObject(n); 118 break; 119 case 'fakeMap': 120 runFakeMap(n); 121 break; 122 case 'map': 123 runMap(n); 124 break; 125 default: 126 throw new Error(`Unexpected method "${method}"`); 127 } 128} 129