Creating and running suites is very easy thanks to the benchmark tool. All we will need is to set up our sets-arr.js file, and we are good-to-go:
var Benchmark = require("benchmark");
var suite = new Benchmark.Suite();
var set = new Set();
var arr = [];
for(var i=0; i < 1000; i++) {
set.add(i);
arr.push(i);
}
suite
.add("array #indexOf", function(){
arr.indexOf(100) > -1;
})
.add("set #has", function(){
set.has(100);
})
.add("array #splice", function(){
arr.splice(99, 1);
})
.add("set #delete", function(){
set.delete(99);
})
.add("array #length", function(){
arr.length;
})
.add("set #size", function(){
set.size;
})
.on("cycle", function(e) {
console.log("" + e.target);
})
.run();
You can see that the setup is pretty self-explanatory. Once we create the new suite, we set up some data for the initial load and then we can add our tests to the suite:
var set = new Set();
var arr = [];
for(var i=0; i < 1000; i++) {
set.add(i);
arr.push(i);
}
To execute this suite, you can run the following command from a Terminal:
node sets-arr.js
The results of the suite are as follows:
Note that the sets are a little faster than the arrays in this setup. Of course, the data that we are using in the tests can also cause variations in the results; you can try this out by switching between the data types that are being stored in the array and the set.