Re: wich is faster
From: Dave (recneps.w.divad_at_elcaro.moc)
Date: 05/24/04
- Next message: Willem: "Re: smallest disk covering a set of points"
- Previous message: CBFalconer: "Re: Creating an operating system"
- In reply to: buda: "wich is faster"
- Next in thread: Joe Seigh: "Re: wich is faster"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 24 May 2004 12:48:50 +0100
buda wrote:
> Wich is (generally/usually) faster: a comparison, or an assignment?
> For example the following pseudo:
>
> flag <- 0
> loop (condition)
> do something
> flag <-1
> endloop
>
> or
>
> flag <- 0
> loop(condition)
> do something
> if (flag = 0)
> flag <- 1
> endif
> endloop
>
>
Nobody seems to have mentioned it, so...
The second will be slower because you're doing a comparison AND and
assignment (because flag=0 is true). Change the comparison to flag<>0
and you have a more realistic test.
Also it depends on the processor. Does it have a zero-register command
(like xor a,a on the z80), or does it have to load a literal 0 from the
code (ld a,0)? Same for the test - does it have some way of setting
flags with a single byte instruction (and a), or does it have to compare
the register with zero then deal with the result of the subtraction (cp
a,0)?
Having said that, flag=0; if (flag==0) flag=1; is pointless - flag is
always going to be 1 at the end so you may as well skip the test and
just assign 1.
On the premature optimisation front - it has to be a judgement call by
the programmer. Optimising something you don't know to be slow should
not be done until you know (a) it is slow and (b) it is a problem. If
you know two algorithms for something, one is faster but slightly less
readable than the other, I'd probably go for the faster one depending on
how much less readable it is. Trivial example - testing for primeness
of n could involve an array of size n(+1 because subtracting 1 from
everything is "unreadable") and a Sieve of Eratosthenes function. That
is going to be substantially slower and much more memory intensive than
an "& 1" and a simple loop dividing n by odd numbers from 3 to sqrt(n).
Depending on the mathematical knowledge of one's peers, the latter may
be unknown and is thus "unreadable", so should the sieve be used because
of that? I think not. I do not accept that readability is an excuse
for deliberately writing crap code, but that there is a balance that
must be reached. I would propose a similar rule to "premature
optimisation is the root of all kinds of evil", namely "excessive
program simplification is also the root of all kinds of evil", including
such crap as "#define BEGIN {", #define END_OF_LINE ;" and so on.
Dave.
- Next message: Willem: "Re: smallest disk covering a set of points"
- Previous message: CBFalconer: "Re: Creating an operating system"
- In reply to: buda: "wich is faster"
- Next in thread: Joe Seigh: "Re: wich is faster"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|