Performance optimization for minElement and maxElement

Paul Backus snarwin at gmail.com
Mon Sep 12 16:26:01 UTC 2022


On Monday, 12 September 2022 at 15:27:25 UTC, Steven 
Schveighoffer wrote:
> This isn't that crazy though. Checking against an absolute 
> minimum or maximum has a cost, one which you may not want to 
> incur.
>
> For instance, uint.min is 0, this might be a common occurrence 
> in some ranges. But int.min is -2billion. That might *never* 
> occur in some ranges. Why waste time checking for something 
> that will never occur in the name of "performance"? For many 
> types and data sets, this is a net pessimization.
>
> And there's not a way to do this shortcut via type wrapping. 
> The only option is to alter the algorithm. Making it opt-in 
> isn't a bad idea, but of course, the API could be badly 
> designed.

It seems like maybe what's desired here is a version of 
[`fold`][1] that allows for early termination. Like, instead of 
just returning the next accumulator value, the callback could 
return a tuple of the next value and a `bool continue`, or 
something.

[1]: https://phobos.dpldocs.info/std.algorithm.iteration.fold.html


More information about the Digitalmars-d mailing list