try catch performance vs additional check

Benchmark created on


Setup

const s = "foooo";
const o = '{"val":"foooo"}';
var resS, resO;

function deserialize1 (sData) {
        try {
            return JSON.parse(sData);
        } catch (oError) {
            return sData;
        }
    }
    
function deserialize2 (sData) {
        if (!sData || sData[0] !== "{") {
        	return sData;
        }
        try {
            return JSON.parse(sData);
        } catch (oError) {
            return sData;
        }
    }

Teardown

console.log(resS);
console.log(resO);

Test runner

Ready to run.

Testing in
TestOps/sec
try catch only
deserialize1(null);
resS = deserialize1(s);
resO = deserialize1(o);
ready
check for plain string
deserialize2(null);
resS = deserialize2(s);
resO = deserialize2(o);
ready

Revisions

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