opEquals needs to return bool

Georg Wrede georg at nospam.org
Fri May 16 14:52:34 PDT 2008


bearophile wrote:
> Edward Diener:
> 
>> IMO, even if it were so, one does not twist programming design for 
>> a performance gain.
> 
> In some situations bools are slower, for example you can try this 
> small program: http://codepad.org/pD22tteK
> 
> if at line 8 you replace: int is_valid, went_off_right_side;
> 
> With a logically more correct: bool is_valid, went_off_right_side;
> 
> The program runs slower (with DMD on my CPU about 4% slower).
> 
> Bools are bytes, while ints are 4 bytes, so sometimes ints are 
> managed faster. I agree that it's better for opEquals to return a 
> bool. In theory the compiler may become a bit smarter and use a 
> size_t to represent a bool where this doesn't change the meaning of 
> the program, but this looks not easy in general. Another possibility 
> is to define a second faster bool type, but having two different 
> bools looks bad in a language like D.

I think bools should be of the fastest type available on the machine. On
x86 that is int. Bytes may spare you some room (only in some special
cases, I might add!!), but they really are slower.

This slowness results from the processor not being able to load and
store bytes as efficiently as ints. A byte store, for example, requires
a load of the other 3 bytes (because addresses are accessable only 4
bytes at a time on current 32 bit processors), then a computation of a
mask, the an and operation, then an alignment operation of the value
we're storing, then oring it with the mask result, and then storing the
4 bytes into memory. (Of course, this is what conceptually happens, and
some of the parts are sort-of optimized away in the pipeline or with
special datalines in the CPU. But still, this is essentially what has to
happen when storing a byte.)

With a language having the Hello World in the hundreds of kilobytes, and
only usable outside of x86 Windows/Linux by happenstance, I
find it peculiar if anybody could even imagine an excuse for having
bool be anything else than int size.

---

The above is an issue separate from that of storage. A programmer may
want to use packed bytes to store boolean values in structs, or even bit
arrays. But that is, and should remain his choice.

---

 From previous experience (the Bit Datatype days), I wouldn't bet on this
changing too soon. But I sincerely hope I'm wrong this time.



More information about the Digitalmars-d mailing list