问题
This is a petty question that will make you cringe, but I'm still curious.
Is it slightly more efficient (for if/then logic) to evaluate an explicit false
over falsy values such a null
or undefined
?
When I try/catch
inside of a function, with the intent of recovering from an unimportant (yet) application-halting error, I typically returned undefined
when the try portion cannot not succeed.
However, below I'm returning false
instead of undefined
:
var parseJSON = function(jsonString)
{
try
{
var obj = JSON.parse(jsonString);
if (obj && typeof obj === "object")
{
return obj;
}
}
catch (error)
{
console.log(`🐛 JSON error, but no need to halt.`);
}
return false; //false will not require coercion later, right?
};
let testInput = `This is NOT JSON!`;
if (parseJSON(testInput))
{
console.log("Success, JSON was parsed");
}
else
{
console.log("Is it faster to get here from an explicit false than a falsy value?")
}
I totally realize that the differences are negligible. Yet, you do have to choose, so why not choose the fastest choice if there is one. Instead of just concluding it doesn't matter, I'd like to give this topic a moment of consideration once and for all.
来源:https://stackoverflow.com/questions/58965352/try-catch-functions-false-versus-falsy