opCmp on a struct keyed by an array of bytes

Ali Çehreli acehreli at yahoo.com
Thu Nov 14 13:18:59 PST 2013


On 11/13/2013 07:46 PM, Charles Hixson wrote:

 > On 11/12/2013 04:47 PM, bearophile wrote:
 >> Charles Hixson:
 >>
 >>> I had tried "return bytes.cmp(b.bytes);" , but it didn't occur to me
 >>> that the error meant I should have used a copy?  Does this syntax
 >>> mean that what's being compared is a dynamic array copy of the
 >>> original static array?
 >>
 >> They are not copies, just slices. In case of doubts take a look at the
 >> generated assembly.
 >>
 >> Bye,
 >> bearophile
 >>
 > My assembly is pretty bad, the last one I was fluent in was i6502...I
 > was never really fluent in m68000.  And those were back when I was using
 > an Apple.
 >
 > OTOH, while slice is a better term for what I meant...generally when one
 > makes a copy of an object, one is only duplicating the pointers to it,
 > and that's what I meant.  (Though since the original was a struct, slice
 > is a much better term.  Still, on a 64 bit machine the and an 8 byte
 > key, the slice is twice the size of the original.  And the only
 > benefit(?) is that if the dup was changed, so would be the original.
 > Which is what the I thought the const at the end of the declaration was
 > supposed to prevent.)

I think what we are agreeing here is that there should be a cmp() 
specialization for fixed-length arrays, both for performance reasons and 
for convenience.

In the absence of that specialization, your for loop works well. 
std.algorithm.cmp is another option but it requires an InputRange. Since 
fixed-length arrays do not satisfy the requirements of InputRange 
(cannot provide popFront()), we must get a slice of all of its elements.

Still, I have a feeling that ldc would be able to use the information 
that the length of the slice is based on a constant expression and 
produce faster code. (No citation known. :p)

Ali



More information about the Digitalmars-d-learn mailing list