Skip to content

Instantly share code, notes, and snippets.

@Chunlin-Li
Created December 2, 2015 02:27
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Chunlin-Li/2606bd813df88eaeee2d to your computer and use it in GitHub Desktop.
Save Chunlin-Li/2606bd813df88eaeee2d to your computer and use it in GitHub Desktop.
node / javascript performance : Set vs Object and Map vs Object

Set vs Object

node version : v4.1.2
platform: Intel I7, 16G DDR3, Ubuntu x64

var theSet = new Set();
start = process.hrtime();
/***********************************/
for(let i = 0 ; i < N; i++ ) {
    let v = i%20;
    if (!theSet.has(v))
        theSet.add(v);
}
/***********************************/
console.log('section 1 : ' + timeUse(start));


obj = {};
start = process.hrtime();
/***********************************/
for(let i = 0 ; i < N; i++) {
    let v = i%20;
    if (!obj[v])
        obj[v] = 1;

}
/***********************************/
console.log('section 2 : ' + timeUse(start));

result :

# N = 1M
section 1 : 28348894ns
section 2 : 13017222ns

# N = 1K
section 1 : 1616666ns
section 2 : 109862ns

conclusion: If unnecessary, use Object instead of Set for performance benefit.

Map vs Object

var themap = new Map();
start = process.hrtime();
/***********************************/
for(let i = 0 ; i < N; i++ ) {
    let v = i%20;
    if (!themap.get(v))
        themap.set(v, i);
}
/***********************************/
console.log('section 1 : ' + timeUse(start));


obj = {};
start = process.hrtime();
/***********************************/
for(let i = 0 ; i < N; i++) {
    let v = i%20;
    if (!obj[v])
        obj[v] = 1;
}
/***********************************/
console.log('section 2 : ' + timeUse(start));

result:

# N = 1M
section 1 : 27290298ns
section 2 : 12362120ns

# N = 1K
section 1 : 1749059ns
section 2 : 63746ns

conclusion: same as Set vs Object

@mesudip
Copy link

mesudip commented May 16, 2022

It should give different result with "x"+v instead of just v.

https://stackoverflow.com/a/62351925/2804342

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment