|
-
January 6th, 2009, 01:03 PM
#4
Re: How to Elegantly code an if()?
 Originally Posted by Cy_
How long does an if condition check take when the result is negative and the if won't need to run?
Anywhere from a few CPU cycles to a few years 100 million executions of the statement is only 1157 executions a second, which (assuming it's a relatively normal if statement) should take a fraction of a microsecond.
Of course, if the test only needs to be executed once, why not execute the check and then store the result in a boolean in your class? Then you can just do:
Code:
public class C
{
readonly bool checkPassed;
public C ()
{
if (StandardIfStatement == ExpectedResult)
checkPassed = true;
// or just do: checkPassed = StandardIfStatement == ExpectedResult;
}
public Method ()
{
if (checkPassed)
DoStuff ();
DoOtherStuff ();
}
}
I'd recommend doing this, not for performance reasons, but it makes it clear that the test is only being performed once and will never change. It makes the intent of your code more obvious.
I measured it with Matlab which must be slower than C# and a simple if statement with negative result comes to 0.000856 seconds after the first several runs to take advantage of the cach! This is a lot and for just 1 M run takes up 850 seconds of CPU time during an 8 hour period!
Remember that matlab is interpreted and thus is *very* slow as compared to a compiled/jitted language. The results are nowhere near comparable. Run the test in C# and see for yourself.
www.monotorrent.com For all your .NET bittorrent needs
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|