Do not micro optimize, make it readable.
I think this is more readable:
bool visible; Boolean.TryParse(this.Request["visible"], out visible); return visible;
readable variable names usually help;) And this implementation actually gives fewer op codes compared to the other two, and I believe that it will execute in fewer cycles, being faster than your attempts.
Thus, this is not only more readable imo, but also faster because it skips the if . The other two have the same op-codes, just switched the logic to check.
[Edit - compiled with Release flags - shorter IL]
If you look at the following three implementations:
public bool Visible1 { get { bool b; return Boolean.TryParse(HttpContext.Current.Request["visible"], out b) && b; } } public bool Visible2 { get { bool b; return Boolean.TryParse(HttpContext.Current.Request["visible"], out b) ? b : false; } } public bool Visible3 { get { bool b; Boolean.TryParse(HttpContext.Current.Request["visible"], out b); return b; } }
will produce the following IL code:
.method public hidebysig specialname instance bool get_Visible1() cil managed { .maxstack 2 .locals init ( [0] bool b) L_0000: call class [System.Web]System.Web.HttpContext [System.Web]System.Web.HttpContext::get_Current() L_0005: callvirt instance class [System.Web]System.Web.HttpRequest [System.Web]System.Web.HttpContext::get_Request() L_000a: ldstr "visible" L_000f: callvirt instance string [System.Web]System.Web.HttpRequest::get_Item(string) L_0014: ldloca.sb L_0016: call bool [mscorlib]System.Boolean::TryParse(string, bool&) L_001b: brfalse.s L_001f L_001d: ldloc.0 L_001e: ret L_001f: ldc.i4.0 L_0020: ret } .method public hidebysig specialname instance bool get_Visible2() cil managed { .maxstack 2 .locals init ( [0] bool b) L_0000: call class [System.Web]System.Web.HttpContext [System.Web]System.Web.HttpContext::get_Current() L_0005: callvirt instance class [System.Web]System.Web.HttpRequest [System.Web]System.Web.HttpContext::get_Request() L_000a: ldstr "visible" L_000f: callvirt instance string [System.Web]System.Web.HttpRequest::get_Item(string) L_0014: ldloca.sb L_0016: call bool [mscorlib]System.Boolean::TryParse(string, bool&) L_001b: brtrue.s L_001f L_001d: ldc.i4.0 L_001e: ret L_001f: ldloc.0 L_0020: ret } .method public hidebysig specialname instance bool get_Visible3() cil managed { .maxstack 2 .locals init ( [0] bool b) L_0000: call class [System.Web]System.Web.HttpContext [System.Web]System.Web.HttpContext::get_Current() L_0005: callvirt instance class [System.Web]System.Web.HttpRequest [System.Web]System.Web.HttpContext::get_Request() L_000a: ldstr "visible" L_000f: callvirt instance string [System.Web]System.Web.HttpRequest::get_Item(string) L_0014: ldloca.sb L_0016: call bool [mscorlib]System.Boolean::TryParse(string, bool&) L_001b: pop L_001c: ldloc.0 L_001d: ret }
source share