In message <(E-Mail Removed)>

CBFalconer <(E-Mail Removed)> wrote:

> pete wrote:

> > > > return (*a > *b) - (*a < *b);

> > > return (*a < *b) ? -1 : (*a > *b);

> >

> > I see two unconditional comparisons and a subtraction in the first,

> > but only two comparisons, with one of them being conditional,

> > in the second.
Actually, both cases will probably only need to have one actual comparison on

most architectures, with a multi-way set of conditions following.

> However the emitted code will often not have any jumps in it (for

> the first), which avoids flushing any instruction queues. I

> learned it from someone, and consider it a trick worth knowing.
Isn't micro-optimisation great?

> The point is that they are both safe, and have a chance to

> simultaneously be efficient and clear. However there may be

> considerable code involved in converting a machine comparison into

> the 0 or 1 representation, in which case the ?: coding will be

> superior.
Also, conditional execution (as found in the ARM) tends to render such jump

avoidance counter-productive, as there are unlikely to be any branches

involved in such a simple condition. The subtraction comes out as the

tedious:

intcmp

LDR a1,[a1]

LDR a2,[a2]

CMP a1,a2

MOVLE a1,#0

MOVGT a1,#1

MOVGE a2,#0

MOVLT a2,#1

SUB a1,a1,a2

MOV pc,lr

Whereas the ? : form wins by 1-4 cycles:

intcmp

LDR a1,[a1]

LDR a2,[a2]

CMP a1,a2

MVNLT a1,#0

MOVLT pc,lr

MOVLE a1,#0

MOVGT a1,#1

MOV pc,lr

--

Kevin Bracey, Principal Software Engineer

Tematic Ltd Tel: +44 (0) 1223 503464

182-190 Newmarket Road Fax: +44 (0) 1223 503458

Cambridge, CB5 8HE, United Kingdom WWW:

http://www.tematic.com/