On Dec 10, 12:21 am, "Sing" <s...@gmail.comwrote:
Dear C Gurus,
I would like to optimise a max() algo that my program uses many times.
Which one is faster or are they the same?
1. #define max(a,b) (((a) (b)) ? (a) : (b))
2. if (a>b) return a
I have a feeling that (1) is faster, but cannot explain why. Can some Gurus
enlighten?
I can tell you that you are doing a bad thing worrying about which of
these two things is faster.
You should write the one that seems the most clear to you, or better
yet, use a system provided max().
The first rule of optimization is: "Don't do it."
The second rule of optimization (for experts only) is: "Don't do it
yet."
Seriously, it is a big mistake to write twiddly things that you think
are going to outsmart the compiler. The chances are very good that
you will:
1. Introduce bugs
2. Make something much harder to maintain
3. Make something that is not any faster anyway
4. Waste a huge amount of time trying to speedup something that does
not need to be sped up.
You should never optimize code without a profile session. You should
never run the profile session unless the code does not meet performace
specifications. It is almost certain that you will be optimizing in
the wrong place if you just willy-nilly start tweaking things. And
both of your proposed solutions are O(1) which means that at best the
performance difference will be a small, constant factor. Unless these
constructs are in a deeply nested loop, you will be unable to measure
the performance differece found by choosing one format over the other
(if, indeed, there is any performance difference).