[racket] How fast is zero? was: Find nth term of a List

From: Stephen Bloch (bloch at adelphi.edu)
Date: Thu Sep 27 16:34:54 EDT 2012

On Sep 27, 2012, at 12:10 PM, Tim Brown wrote:

> What is the difference in correctness between "(= x 0)" vs. "(zero? x)"?

None, although neither one is equivalent to "(eq? 0 x)".

> Fast is relevant to some questions (solutions) I have -- terminating tight
> loops etc. And given a choice of (eq? 0 x), (= 0 x) and (zero? x), which
> would, and which should take the shortest time to perform 10^12 times?

If you're looking for elements specified by their position in a list of 10^12 elements, you should probably be using a different data structure in the first place :-)

For almost any program I can think of, the performance difference among (eq? 0 x), (= 0 x), and (zero? x) is likely to be insignificant by comparison with other parts of the program.

> Maybe I'm thinking a bit too much like a C programmer -- (!x)... works for
> me as a test in so many ways; that I tend to want to use something like it
> when I'm writing in other languages. (Where I should be using zero? false?
> and/or null?).

Yes, C programmers routinely rely on all sorts of machine-dependent assumptions: almost any datum can be viewed as an integer, null pointers are represented by the same bit pattern as the integer 0, the floating-point number 0.0 is represented by the same bit pattern as the integer 0, etc.

I've worked on systems that intentionally used the bit pattern for 1, not 0, as a null pointer (it was a word-addressable machine, and if you tried to dereference an odd-numbered address, it would crash immediately, as one would expect of dereferencing a null pointer).  And on MANY systems (including Racket), the floating-point number 0.0 doesn't necessarily resemble the integer 0.


Stephen Bloch
sbloch at adelphi.edu



Posted on the users mailing list.