std.container.RedBlackTree versus C++ std::set

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 15 14:59:44 PST 2013


On Fri, Feb 15, 2013 at 11:49:53PM +0100, monarch_dodra wrote:
> On Friday, 15 February 2013 at 22:06:55 UTC, Steven Schveighoffer
> wrote:
> >With opcmp:
> >
> >int opCmp(int a, int b)
> >{
> >   return a - b;
> >}
> 
> Genius!
> 
> Now I feel bad for every time I've done integral opCmp with double
> ternary operators :(

You know that this is the origin of C's strcmp, right? Ever wondered why
the C standard says that it returns <0, 0, or >0, as opposed to fixed
values like -1, 0, 1?

Now you know why: it's because you could implement strcmp by repeatedly
subtracting respective pairs of characters from the two strings, and
return the result when it's no longer zero (in some CPUs' assembly
language, this is a single branch-on-nonzero instruction). No need for
extraneous overhead to convert the result of the comparison into fixed
values of any sort.

D simply inherited from the genius of C's original designers. :)

Of course, this optimization may no longer be relevant in today's CPU's,
due to pipelining, hazards, branch prediction, etc..


T

-- 
If creativity is stifled by rigid discipline, then it is not true creativity.


More information about the Digitalmars-d-learn mailing list