Efficient empty collection test

Benchmark created on


Description

Check if a loop or length > 0 is more efficient or not for checking if a collection is empty or not

Setup

function isEmptyLength(obj) {
	return obj.length === 0
}

function isEmptyLoop(obj) {
	for (const _ in obj) {
    	return false
  	}

 	return true
}

function isArray(arr) {
	return Array.isArray(arr);
}

function newEmpty(obj) {
	return isArray(obj) ? isEmptyLength(obj) : isEmptyLoop(obj);
}

function newEmpty2(obj) {
	return isArray(obj) ? obj.length === 0 : isEmptyLoop(obj);
}

const short = ["hello", "bye", 1,2,3,4,5,6,7,8,9,10,11, "this is good!"];
const big = [];
for (let i = 0; i <= 100_000; i++) {
    big.push(i);
}

Test runner

Ready to run.

Testing in
TestOps/sec
With length and short array
isEmptyLength(short)
ready
With length and big array
isEmptyLength(big)
ready
With loop and short array
isEmptyLoop(short);
ready
With loop and big array
isEmptyLoop(big);
ready
With newempty and short array
newEmpty(short);
ready
With newempty and big array
newEmpty(big);
ready
With newempty2 and short array
newEmpty2(short);
ready
With newempty2 and big array
newEmpty2(big);
ready
Without function call and short array
short.length === 0
ready
Without function call and big array
big.length === 0
ready
Check length with if (short)
if (short.length) {
	
}
ready
Check length with if (big)
if (big.length) {
	
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.