Skip to content

Instantly share code, notes, and snippets.

@dejurin
Created August 22, 2023 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejurin/6c3ac1da6fefb5d37a07457a93f77425 to your computer and use it in GitHub Desktop.
Save dejurin/6c3ac1da6fefb5d37a07457a93f77425 to your computer and use it in GitHub Desktop.
Array is Empty: benchmark ways
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite();
console.log('benchmark');
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
suite
.add('Using length property', function() {
emptyArray.length === 0;
})
.add('Using Array.isArray and length', function() {
Array.isArray(emptyArray) && emptyArray.length === 0;
})
.add('Using ! operator', function() {
!emptyArray.length;
})
.add('Using JSON.stringify', function() {
JSON.stringify(emptyArray) === '[]';
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.run({ async: true });
/*
Chip: Apple M1 Max
Memopry: 32 GB
*/
/*
Using length property x 1,034,364,853 ops/sec ±0.16% (101 runs sampled)
Using Array.isArray and length x 1,028,668,071 ops/sec ±0.28% (96 runs sampled)
Using ! operator x 1,033,705,825 ops/sec ±0.18% (100 runs sampled)
Using JSON.stringify x 18,834,958 ops/sec ±0.19% (96 runs sampled)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment