Array declaration VS Object.keys()

Benchmark created on


Description

Based on leetcode problem https://leetcode.com/problems/roman-to-integer/

Purpose of the test is to determine which type of array declaration is faster

Test runner

Ready to run.

Testing in
TestOps/sec
Array declaration
function romanToInt(s) {
    let modString = s;
    let result = 0;
    const romanInt = {
        "CM": 900,
        "CD": 400,
        "XC":90,
        "XL":40,
        "IX":9,
        "IV":4,
        "M":1000,
        "D":500,
        "C":100,
        "L":50,
        "X":10,
        "V":5,
        "I":1
    };
    const romanIntArray = ["CM","CD","XC","XL","IX","IV","M","D","C","L","X","V","I"];
    for (let i = 0; i < 6; i++) {
        if (modString.includes(romanIntArray[i])) {
            modString = modString.replace(romanIntArray[i], "");
            result = result + romanInt[romanIntArray[i]];
        }
    }
    for (let i = 0; i < modString.length; i++) {
        result = result + romanInt[modString[i]];
    }
    return result;
    
};
romanToInt("MCMXCIV");
ready
Using Object.keys() to get an array
function romanToInt(s) {
    let modString = s;
    let result = 0;
    const romanInt = {
        "CM": 900,
        "CD": 400,
        "XC":90,
        "XL":40,
        "IX":9,
        "IV":4,
        "M":1000,
        "D":500,
        "C":100,
        "L":50,
        "X":10,
        "V":5,
        "I":1
    };
    const romanIntArray = Object.keys(romanInt);
    for (let i = 0; i < 6; i++) {
        if (modString.includes(romanIntArray[i])) {
            modString = modString.replace(romanIntArray[i], "");
            result = result + romanInt[romanIntArray[i]];
        }
    }
    for (let i = 0; i < modString.length; i++) {
        result = result + romanInt[modString[i]];
    }
    return result;
    
};
romanToInt("MCMXCIV");
ready

Revisions

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