Anagram test

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) {
    const leftChars = new Map();
    for (const leftChar of left) {
        if (!leftChars.has(leftChar)) {
            leftChars.set(leftChar, 0);
        }
        leftChars.set(leftChar, leftChars.get(leftChar) + 1);
    }
    for (const rightChar of right) {
        if (!leftChars.has(rightChar)) {
            return false;
        }
        leftChars.set(rightChar, leftChars.get(rightChar) - 1);
    }

    return [...leftChars.values()].every(val => val === 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.