While developing ASP.NET applications I often need to parse a boolean value given in string form, e.g. from a query string like ?visible=true
I found two solutions to implement the parsing:
bool Visible
{
get
{
bool b;
return Boolean.TryParse(this.Request["visible"], out b) && b;
}
}
or
bool Visible
{
get
{
bool b;
return Boolean.TryParse(this.Request["visible"], out b) ? b : false;
}
}
How do you think which way is preferred? And probably faster?
P.S. It’s not a micro-opt, I just want to get know
P.P.S. I’m not familiar with IL so decided to ask here
Don’t micro optimize, make it readable.
I think this is more readable:
readable variable names usually helps 😉 And this implementation actually yields fewer op codes compared to the other two, and I assume it will perform in fewer cycles, being faster than both your attempts.
So, it’s not only more readable imo, but also faster since it skips the
ifstatement. The other two have equal op codes, just switched the logic around on the checking.[Edit – compiled with Release flags – shorter IL]
If you look at the three following implementations:
will yield the following IL code: