Re: [RFC] Add clamp function
| From: | Kyle Katarn | Date: | Fri, 22 Aug 2025 17:29:46 +0000 |
| Subject: | Re: [RFC] Add clamp function | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128532@lists.php.net to get a copy of this message | ||
2025-08-22 at 13:30, Juris Evertovskis <juris@glaive.pro> wrote:
> *From:* Kyle Katarn <kylekatarnls@gmail.com>
> *Sent:* Friday, August 22, 2025 11:02 AM
> *To:* Christoph M. Becker <cmbecker69@gmx.de>
> *Cc:* Tim Düsterhus <tim@bastelstu.be>; PHP Internals <
> internals@lists.php.net>
> *Subject:* Re: [PHP-DEV] [RFC] Add clamp function
>
> > I created https://wiki.php.net/rfc/clamp_v2 (re-using most
> > of the info
> from https://wiki.php.net/rfc/clamp).
>
> Hey,
>
>
>
> I’m not against adding such a function, but I noticed that the RFC says
>
>
>
> > some of which use min
> > <https://www.php.net/manual/en/function.min.php>
> and max <https://www.php.net/manual/en/function.max.php>
> to check the
> bound, which is costly and slow when called often
>
>
>
> What makes them slow? If we can create a significantly faster
> “ÄI"BQˆüÕTclamp, can
> we use the same optimizations to improve min and max?
>
>
>
> BR,
>
> Juris
>
I taked it from https://wiki.php.net/rfc/clamp and from
what I understand
reading the code: min and max support variadic array of parameters, or a
single array value, so min($max, max($min, $value)) will result in 2 loops,
plus if-else paths depending on the type. While the current implementation
of clamp accepts only 1 value, 1 min and 1 max, so it just does $value <
$min ? $min : $value > $max ? $max : $value, which is way less work.
Also from my point of view, min($max, max($min, $value)) has a
counter-intuitive reading when used to clamp a value.