Manual toString VS JSON.stringify()

Benchmark created on


Setup

function getType(x) {
    if(x === null) return "Null";
    if(x === void 0) return "Undefined";
    return x.constructor.name;
}

function toStr(val, opts){
//@bye-csavier
    let typeOf = getType(val); 
  
    if(typeOf == 'String'){
        if(opts?.quoteString) return `"${val}"`;
        return val;
    }
    if( typeOf == "Object")
    {
        let str = "{";
        let keys = Object.keys(val), len =  keys.length;
        for(let i=0; i<len-1; ++i){
            str += `"${keys[i]}":${toStr(val[keys[i]], opts)},`;
        }
        str += `"${keys[len-1]}":${toStr(val[keys[len-1]], opts)}`;
        return str+"}";
    }
    if( typeOf == "Array"){
        let str = "[";
        let len =  val.length;
        for(let i=0; i<len-1; ++i){
            str += `${toStr(val[i], opts)},`;
        }
        str += `${toStr(val[len-1], opts)}`;
        return str+"]";
    }
    if(typeOf == "Symbol"){
        return val.toString();
    }
    if(val === null) return "null";
    if(val === undefined) return "undefined";
    if(val === true) return "true";
    if(val === false) return "false";
    
    return (""+val);
}

let tests = [
        [1,2,,4,5,undefined],
        {a:2, b:{c:4,d:undefined}, c:{d:2}, d:undefined},
        2,
        "hi",
        {a:2, b:[2,"hi"]},
        ()=>{return "ok"}
]

Test runner

Ready to run.

Testing in
TestOps/sec
toStr() manual
for(let i=0, len = tests.length; i<len; ++i){
	toStr(tests[i])
}
ready
JSON.stringify()
for(let i=0, len = tests.length; i<len; ++i){
	JSON.stringify(tests[i])
}
ready

Revisions

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