For example, my situation:
I’m getting an input of “0”, “1”, “true” or “false”. (in any case)
what is preferred on terms of performance, code reading, any basically best-practice:
bool func(string param)
{
string lowerCase = param;
to_lower(lowerCase);
if (lowerCase == "0" || lowerCase == "false")
{
return false;
}
if (lowerCase == "1" || lowerCase == "true")
{
return true;
}
throw ....
}
or:
bool func(string param)
{
string lowerCase = param;
to_lower(lowerCase);
regex rxTrue ("1|true");
regex rxFalse ("0|false");
if (regex_match(lowerCase, rxTrue)
{
return true;
}
if (regex_match(lowerCase, rxFalse)
{
return false;
}
throw ....
}
The second is somewhat clearer, and easier to extend (e.g.: accepting
"yes"and"no", or prefixes, with"1|t(?:rue)?)"and"0|f(?:alse)?". With regards to performance, the second can (andshould) be made significantly faster by declaring the
regexstatic(and
const, while you’re at it), e.g.:Note too that by specifying case insensitivity, you’ll not have to
convert the input to lower case.