Domanda

I was reading the source code of lcc, in alloc.c:

if ((ap->next = freeblocks) != NULL) {
   freeblocks = freeblocks->next;
   ap = ap->next;
}

Why not

if (freeblocks != NULL) {
   ap->next = freeblocks;
   freeblocks = freeblocks->next;
   ap = ap->next;
}

Would the latter cause extra cost?

È stato utile?

Soluzione 3

Performance is a function of design in an optimizing compiler.

A number of years ago I reviewed a book manuscript for a publisher in which the author showed all kinds of programming tricks (like side effect assignments) that he claimed produced faster code.

I compiled his versions on several compilers and showed that none of his tricks produced faster code and most resulted in slower code.

You should always write the clearest code and let the compiler do the optimizing for you.

Assignments within if statements are a bad programming practice. Using = instead of == is a common error. Consistently avoiding side effect assignments makes these errors easier to spot.

Your mistake in translation shows how unclear the original code is.This kind of bad code often springs from assembly language programmers.

Your revised version translates literally into something like this (my pseudo assembly code)

MOV  freeblocks, next(R0)
TEST next(R0)                      ; Test for zero
JUMPNE TEST

While the literal translation of the original is more like:

MOV  freeblocks, next(R0)
JUMPNE TEST

Most systems test for zero as part of the move instruction. In theory, the original version is one instruction shorter.

However, any optimizing compiler will be smart enough to remove the redundant TEST.

Coding to outguess the compiler is a waste of time, effort, and clarity.

Altri suggerimenti

The code snippets you post are not identical in function.

The first assigns freeblocks to ap->next, and if it is not NULL, proceeds with the other two statements.

The second, which you proposed, does not assign freeblocks to ap->next if freeblocks is NULL, and in fact does nothing in this case. This is not the same.

You could change your proposal to the following, which is functionally equivalent:

ap->next = freeblocks;
if (freeblocks != NULL) {
   freeblocks = freeblocks->next;
   ap = ap->next;
}

This avoids the assignment-as-part-of-a-condition which some would consider bad style. It is unlikely to cause any extra 'cost' assuming you mean execution speed or code size when compiled.

If you fixed your 2nd example to be functionally identical, say

ap->next = freeblocks;
if (freeblocks != NULL) {
    freeblocks = freblocks->next;
    ap = ap->next;
}

and as you're worried about speed, I'd expect you to have compiler optimzation on...

then the answer to your is-it-faster question would be: probably not.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top