I’m wondering what is the fastest way that I can write some code. I have a loop which executes an add on some ints. The loop will be executed many, many times and so I’ve thought of making comparisons to check if any operands are zero, so they shouldn’t be considered to be added, as follows:
if (work1 == 0)
{
if (work2 == 0)
tempAnswer = toCarry;
else
tempAnswer = work2 + toCarry;
}
else if (work2 == 0)
tempAnswer = work1 + toCarry;
else
tempAnswer = work1 + work2 + toCarry;
I believe the nested IF at the top is already an optimisation, in that it is faster than writing a series of comparisons with &&’s, as I would be checking (work1 == 0) more than once.
Sadly, I wouldn’t be able to say just how frequently work1 and work2 would be zero, so assume it’s likely to be a balanced distribution of each possible outcome of the IF statement.
So, in light of that, is the above code faster than just writing tempAnswer = work1 + work2 + toCarry or would all the comparisons possibly cause a lot of drag?
Thanks
That is nonsense.
Comparing two integers takes just as long as adding two integers.
Doing a branch takes much, much longer than the add (on many, admittedly older (See comments), CPUs)
On more modern architectures, the bottleneck is accessing values from memory, so this scheme is still not helping where it’s needed.
Also, think about this logically — why single out zero as the one value you treat as a special case? Why not also check for one, and use
tempAnswer++? When you consider all the possibilities, you can see it’s a pointless exercise.