Skip to content

Commit

Permalink
feat(bench): test object vs map
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Mar 17, 2023
1 parent e93b5c3 commit 9b88716
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
5 changes: 3 additions & 2 deletions demo/es-bench/bench.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const count = 1_000_000;
export const bench = (name: string, func: () => void): void => {
globalThis.gc?.();
const startMemory = process.memoryUsage.rss();
const startTime = performance.now();
for (let i = 1_000_000; i; i--) {
for (let i = count; i; i--) {
func();
}
const duration = performance.now() - startTime;
const runPerSec = Math.round( 1_000_000 / duration * 1000);
const runPerSec = Math.round( count / duration * 1000);
const memoryUsage = Math.round((process.memoryUsage.rss() - startMemory) / 10) / 100;

console.log(`run ${name} ${runPerSec.toLocaleString()}/s with ${memoryUsage.toLocaleString()}kb`);
Expand Down
60 changes: 60 additions & 0 deletions demo/es-bench/object-vs-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable camelcase */

import {bench} from './bench.js';

const size = 1_000;

let userListRecord: Record<string, Record<string, string>> = {};
let userListMap = new Map<string, Map<string, string>>();

function test_make_map() {
userListMap = new Map<string, Map<string, string>>();
for (let i = size; i; i--) {
const userId = 'user_' + i;

const user = new Map();
user.set('user', userId);
user.set('fname', 'ali');
user.set('lname', 'md');
user.set('email', '[email protected]');
user.set('token', '1234abcd');

userListMap.set(userId, user);
}
}

function test_make_obj() {
userListRecord = {};
for (let i = size; i; i--) {
const userId = 'user_' + i;
userListRecord[userId] = {
user: userId,
fname: 'ali',
lname: 'md',
email: '[email protected]',
token: '1234abcd',
};
}
}

function test_access_map() {
if (userListMap.get('user_' + size / 2)!.get('user') !== 'user_' + size / 2) throw new Error('not_match');
}

function test_access_obj() {
if (userListRecord['user_' + size / 2]['user'] !== 'user_' + size / 2) throw new Error('not_match');
}

bench('test_make_map_1st', test_make_map);
bench('test_make_obj_1st', test_make_obj);
bench('test_access_map_1st', test_access_map);
bench('test_access_obj_1st', test_access_obj);

bench('test_make_map_2nd', test_make_map);
bench('test_make_obj_2nd', test_make_obj);
bench('test_access_map_2nd', test_access_map);
bench('test_access_obj_2nd', test_access_obj);

globalThis.document?.body.append(' Done. Check the console.');

0 comments on commit 9b88716

Please sign in to comment.