Skip to content

Instantly share code, notes, and snippets.

@kuanyui
Last active February 5, 2020 03:56
Show Gist options
  • Save kuanyui/0f0df5b49edd9ebead1f4fc44b4a6ec4 to your computer and use it in GitHub Desktop.
Save kuanyui/0f0df5b49edd9ebead1f4fc44b4a6ec4 to your computer and use it in GitHub Desktop.
[JavaScript] Benchmark Accessing Performance among Array, Object, Map. (Run in browser or node)
const OBJ = {};
const ARR = [];
const MAP = new Map();
const KEYS = [];
LENGTH = 100000;
for (let i=0; i<LENGTH; i++) {
const key = i; // Use int as key
const val = { name: 'foo', id: Math.random(), count: 0 };
KEYS.push(key);
OBJ[key] = val;
MAP.set(key, val);
ARR[i] = val;
}
function dummy(val) {
val.count += 1;
}
const RAND_I = [];
const RAND_KEYS = [];
while (RAND_I.length <= LENGTH) {
const i = Math.round(Math.random() * (LENGTH-1));
RAND_I.push(i);
RAND_KEYS.push(KEYS[i]);
}
console.log('==============')
console.log('int as keys')
console.log('==============')
console.time('Array')
for (const i of RAND_I) {
dummy(ARR[i]);
}
console.timeEnd('Array')
console.time('Map')
for (const k of RAND_KEYS) {
dummy(MAP.get(k));
}
console.timeEnd('Map')
console.time('Object')
for (const k of RAND_KEYS) {
dummy(OBJ[k]);
}
console.timeEnd('Object')
const OBJ = {};
const ARR = [];
const MAP = new Map();
const KEYS = [];
LENGTH = 100000;
for (let i=0; i<LENGTH; i++) {
const key = 'k' + i; // Use string as key
const val = { name: 'foo', id: Math.random(), count: 0 };
KEYS.push(key);
OBJ[key] = val;
MAP.set(key, val);
ARR[i] = val;
}
function dummy(val) {
val.count += 1;
}
const RAND_I = [];
const RAND_KEYS = [];
while (RAND_I.length <= LENGTH) {
const i = Math.round(Math.random() * (LENGTH-1));
RAND_I.push(i);
RAND_KEYS.push(KEYS[i]);
}
console.log('==============')
console.log('string as keys')
console.log('==============')
console.time('Array')
for (const i of RAND_I) {
dummy(ARR[i]);
}
console.timeEnd('Array')
console.time('Map')
for (const k of RAND_KEYS) {
dummy(MAP.get(k));
}
console.timeEnd('Map')
console.time('Object')
for (const k of RAND_KEYS) {
dummy(OBJ[k]);
}
console.timeEnd('Object')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment