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.
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
The performance depends on the characteristic of the input data.
If you can expect low percentage of duplicates in your data, Set is faster.
Refer to https://github.com/jngbng/set-vs-object