Performance optimization for minElement and maxElement

Steven Schveighoffer schveiguy at gmail.com
Mon Sep 12 14:15:45 UTC 2022


On 9/12/22 7:53 AM, Sergey wrote:
> On Monday, 12 September 2022 at 11:46:23 UTC, Ali Çehreli wrote:
>>
>> I am not that silly. :) What I meant is "as soon as they see e.g. 0". 
>> Say, at the third element of a million-element range...
>>
> 
> In case zero will be the last element - the search should make an extra 
> comparisons “if currentElement = T.minimum” which double operations..
> Isn’t it?

It could only make comparisons when assigning the "current minimum". I 
don't think it would cost that much. Complexity would be the same anyway.

One thing that is worrisome though, is the fact that `min` and `max` 
aren't always the minimum and maximum bit patterns available. So 
short-cutting the search might do something you don't want.

e.g. an enum which defines a bitfield might have values of 1, 2, 4, 8, 
but instances of the enum might go all the way up to 15 (all bits set). 
However, the `.max` value would be 8. And in other cases, the enum truly 
may just be an enum, where the `.max` value is the maximum value, but 
you'd have to defensively check for the max representable value, making 
it perform this check for no reason.

A possibility is to provide an overload that accepts the absolute 
minimum or maximum, and only then does it do the extra comparisons.

-Steve


More information about the Digitalmars-d mailing list