This is one of the easier Optimizations that may be done when dealing with often used code (large data sets or large loops), and sometimes the most over looked one, and work's on any platform. The trick to pulling it off well involves a little data or loop analysis though.
Take the following compound if
May run much faster (see explaination after) if it's reorganized as followsif (enddate >= selecteddatevalue
&& startdate <= selectedatevalue
&& activeflag == true
&& state.compareto(selectedstate) == 0)
{
...do something
}
The basic idea to if/when you should reorganize compound IF's is based on analyising the data, to determine which condition would eliminate the the most, (be true the least) and code that if first, the second most emlinating condition second, and so on.if (activeflag == true)
if (state.compareto(selectedstate) == 0)
if (startdate <= selectedatevalue)
if (enddate >= selectedatevalue)
{
...do something
}
In the case where I first learned this the difficult way by practical experience, I cut the run time of a process from near 20 minutes to 2, by just reorganizing a single IF with six conditions, into 6 cascading IF's where the first IF tended to be false most often. You typicaly do have to do a little data research to determine that, with SQL servers thats a simple matter, but if it's flat file data, that can be done by just temporalily adding countes for each part of the condition into your code one time to get results, to find the most often false condition, and then the next most often false, and so on.
The reason this works is a simple matter. In the compound if example, it's having to check all 4 data types, on every iteration of the data or loop (think of this of it as doing 4 compare instruction for every time no matter what) . In the reorganized example, the first if when false, prevents the other three if's from ever being exceuted at all. There for, less machine instructions are actualy done on the CPU. (It eliminates 3 compare instructions, when the first is false). Don't rely on CPU Optimizations or Compilers one in this case, as actualy reorganizing the IF when (or if) possible, procudes faster results then what those Optimizers can tend to accomplish.