Anagram test (v2)

Revision 2 of this benchmark created on


Setup

const limit = 10000;
const heart = "heart"
const earth = "earth"
const count = 1000;
const heartLong = new Array(count).map(_ => heart).join('');
const earthLong = new Array(count).map(_ => earth).join('');

Test runner

Ready to run.

Testing in
TestOps/sec
loop
function isAnagram(a, b) {
    if (a.length !== b.length) return false;
    const aChars = a.split('').sort();
    const bChars = b.split('').sort();
    for (let ix = 0; ix < aChars.length; ix++) {
        if (aChars[ix] !== bChars[ix]) return false;
    }
    return true;
}


isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
ready
join and compare
function isAnagram(a, b) {
    if (a.length !== b.length) return false;
    return a.split('').sort().join('') === b.split('').sort().join('');
}

isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
ready
hashmap
function isAnagram(left, right) {
    if (left.length !== right.length) return false;
    const charMap = new Map();
    for (const leftChar of left) {
        charMap.set(leftChar, (charMap.get(leftChar) || 0) + 1);
    }
    for (const rightChar of right) {
    	if (!charMap.get(rightChar)) return false; // Early return if a character count goes to falsy
        charMap.set(rightChar, (charMap.get(rightChar) || 0) - 1);
        
    }

    return [...charMap.values()].every(val => val === 0); // Check that all counts are 0.
}



isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
ready
object-map
function isAnagram(left, right) {
	if (left.length !== right.length) return false;
    const charMap = {};
    for (const leftChar of left) {
        charMap[leftChar] = (charMap[leftChar] || 0) + 1;
    }
    for (const rightChar of right) {
    	if (!charMap[rightChar]) return false; // Early return if a character count is falsy
        charMap[rightChar] = (charMap[rightChar] || 0) - 1;        
    }

    return Object.values(charMap).every(v => v === 0);
}


isAnagram(heartLong, earthLong)
isAnagram("x" + heartLong, earthLong)
isAnagram(heartLong + "x", earthLong)
isAnagram("heart", "earth")
isAnagram("anagram", "nagaram")
isAnagram("heartt", "earthh")
isAnagram("", "")
isAnagram("", "1")
isAnagram("", "\0")
ready

Revisions

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