Is it better to assign boolean to local variable and reuse it or duplicate comparison using if?
asp.net-mvc-4, boolean, c#, performance, razor
Solution
In this case, yes, to document, what this magic condition means:
bool wrapInTimeout = i > 1;
And don't call it `higherThanOne`. That would be an unhelpful name.
Name your variables according to what they represent, not according to how they were computed.
Problem
Imagine I have this code(Razor syntax): ``` <script type="text/javascript"> @{ var i = 0; foreach (var notify in @Model) { if (i > 1) // <------ First comparison { <text>setTimeout(function() {</text> } <text> // JavaScript </text> if (i > 1) // <------ Second same comparison { <text>}, 1000 * @i);</text> } i++; } } </script> ``` Notice that `int i` is compared twice. Is it better to assing result of first comparison to local variable and then check it's value or do a second simple comparison? Like this: ``` <script type="text/javascript"> @{ var i = 0; foreach (var notify in @Model) { bool higherThanOne = i > 1; if (higherThanOne) { <text>setTimeout(function() {</text> } <text> // JavaScript </text> if (higherThanOne) { <text>}, 1000 * @i);</text> } i++; } } </script> ``` I came across similiar situation many times and I'm not sure what's better. I want to avoid assigning code to variables because of unfriendly Razor + JavaScript concatenation syntax.